我有一个带有状态栏的 WPF 应用程序。
<StatusBar Grid.Row="1"
Height="23"
Name="StatusBar1"
VerticalAlignment="Bottom">
<TextBlock Name="TextBlockStatus" />
</StatusBar>
我想在那里显示文本,并在执行少量工作时切换到沙漏等待光标。
这段代码将更新光标,但StatusBar的文本不会更新...
Cursor = Cursors.Wait
TextBlockStatus.Text = "Loading..."
System.Threading.Thread.Sleep(New TimeSpan(0, 0, 3))
TextBlockStatus.Text = String.Empty
Cursor = Cursors.Arrow
更新
如果我这样做,它可以工作,但我对这个解决方案并不满意。有更简单的方法吗?
Delegate Sub Load1()
Sub Load2()
System.Threading.Thread.Sleep(New TimeSpan(0, 0, 3))
End Sub
Dim Load3 As Load1 = AddressOf Load2
Sub Load()
Cursor = Cursors.Wait
TextBlockStatus.Text = "Loading..."
Dispatcher.Invoke(DispatcherPriority.Background, Load3)
TextBlockStatus.Text = String.Empty
Cursor = Cursors.Arrow
End Sub
我更希望它看起来像这样...
Sub Load()
Cursor = Cursors.Wait
TextBlockStatus.Text = "Loading..."
'somehow put all the Dispatcher, Invoke, Delegate,
AddressOf, and method definition stuff here'
TextBlockStatus.Text = String.Empty
Cursor = Cursors.Arrow
End Sub
甚至更好的是...
Sub Load()
Cursor = Cursors.Wait
ForceStatus("Loading...")
System.Threading.Thread.Sleep(New TimeSpan(0, 0, 3))
ForceStatus(String.Empty)
Cursor = Cursors.Arrow
End Sub
Sub ForceStatus(ByVal Text As String)
TextBlockStatus.Text = Text
'perform magic'
End Sub
更新
我也尝试将TextBlock绑定到公共属性,并实现INotifyPropertyChanged,如IanGilham建议的那样。但是无法正常工作。
XAML:
<TextBlock Text="{Binding Path=StatusText}"/>
Visual Basic:
Imports System.ComponentModel
Partial Public Class Window1
Implements INotifyPropertyChanged
Private _StatusText As String = String.Empty
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Property StatusText() As String
Get
Return _StatusText
End Get
Set(ByVal value As String)
_StatusText = value
OnPropertyChanged("StatusText")
End Set
End Property
Shadows Sub OnPropertyChanged(ByVal name As String)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(name))
End Sub
...
Sub Load()
...
Cursor = Cursors.Wait
StatusText = "Loading..."
System.Threading.Thread.Sleep(New TimeSpan(0, 0, 3))
StatusText = String.Empty
Cursor = Cursors.Arrow
...
End Sub
...