我正在使用MVVM模式,因此我的ViewModel几乎不知道呈现模型给用户的视图(UI)是什么。
假设我在ViewModel中有以下方法:
public void backgroundWorker_ReportProgress(object sender, ReportProgressArgs e)
{
this.Messages.Add(e.Message);
OnPropertyChanged("Messages");
}
在我的视图中,我有一个绑定到 ViewModel 的 Messages 属性(一个 List<string>
)的 ListBox。通过调用 PropertyChangedEventHandler
,OnPropertyChanged
扮演了 INotifyPropertyChanged
接口的角色。
我需要确保 OnPropertyChanged
在 UI 线程上被调用 - 我该如何做到这一点?我尝试了以下方法:
public Dispatcher Dispatcher { get; set; }
public MyViewModel()
{
this.Dispatcher = Dispatcher.CurrentDispatcher;
}
然后在 OnPropertyChanged
方法中添加以下内容:
if (this.Dispatcher != Dispatcher.CurrentDispatcher)
{
this.Dispatcher.Invoke(DispatcherPriority.Normal, new ThreadStart(delegate
{
OnPropertyChanged(propertyName);
}));
return;
}
但这并没有起作用。有什么想法吗?