我最近下载了 MahApps.Metro 包来玩 Metro Design 和 MVVM。
在项目中,他们创建了 ViewModel:
DataContext = new MainWindowViewModel(Dispatcher);
看起来像这样:
public class MainWindowViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private readonly Dispatcher _dispatcher;
public bool Busy { get; set; }
public MainWindowViewModel(Dispatcher dispatcher)
{
Busy = true;
_dispatcher = dispatcher;
var wc2 = new WebClient();
wc2.DownloadStringCompleted += WcDownloadStringCompleted2;
wc2.DownloadStringAsync(new Uri("http://ws.audioscrobbler.com/2.0/?method=chart.gethypedtracks&api_key=b25b959554ed76058ac220b7b2e0a026&format=json"));
}
private void WcDownloadStringCompleted2(object sender, DownloadStringCompletedEventArgs e)
{
try
{
var x = JsonConvert.DeserializeObject<TrackWrapper>(e.Result);
_dispatcher.BeginInvoke(new Action(() =>
{
Busy = false;
}));
}
catch (Exception ex)
{
}
}
}
我剪掉了一些部分,但代码的工作方式与此处显示的一样。所以他们基本上创建了一个线程,在线程结束之前,他们将 Busy-Property 设置为 false(没有触发任何事件)。
在 XAML 中,他们将此属性绑定到忙指示符:
<Controls:ProgressRing IsActive="{Binding Busy}" VerticalAlignment="Center" HorizontalAlignment="Center" />
一切正常,控件随着属性的变化而变化。
但现在我想一开始就复制这个。XAML 和设置 DataContext 是相等的。我的 ViewModel 看起来像这样(这次是 VB,但不应该有所作为):
Public Class testmodel
Implements INotifyPropertyChanged
Private _busy As Boolean = True
Public Sub New(dispatcher As Windows.Threading.Dispatcher)
Dim t1 As Thread = New Thread(Sub()
'Emulate Progress
System.Threading.Thread.Sleep(2000)
dispatcher.BeginInvoke(New Action(Sub()
Busy = False
End Sub))
End Sub)
t1.Start()
End Sub
Public Property Busy As Boolean
Get
Return _busy
End Get
Set(value As Boolean)
NotifyPropertyChanged(Nothing)
_busy = value
End Set
End Property
Protected Sub NotifyPropertyChanged(info As [String])
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))
End Sub
Public Event PropertyChanged(sender As Object, e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
结束类
所以我创建了一个新线程,将其停止 2 秒,然后更改 Busy-Property。首先,我没有触发事件(与原始事件一样),但什么也没有发生。然后我添加了这条线来触发事件,但什么也没有发生。
我在监督什么吗?