在我使用 MVVM 模式编写的 WPF 应用程序中,我有一个后台进程来做这件事,但需要从它获取状态更新到 UI。
我使用的是 MVVM 模式,因此我的 ViewModel 实际上对向用户呈现模型的视图 (UI) 一无所知。
假设我的 ViewModel 中有以下方法:
public void backgroundWorker_ReportProgress(object sender, ReportProgressArgs e)
{
this.Messages.Add(e.Message);
OnPropertyChanged("Messages");
}
在我看来,我有一个绑定到 Messages 属性的 ListBox(List<string>
)的视图模型。OnPropertyChanged
履行的角色INotifyPropertyChanged
接口通过调用PropertyChangedEventHandler
.
我需要确保OnPropertyChanged
在 UI 线程上调用 - 我该如何执行此操作?我尝试过以下方法:
public Dispatcher Dispatcher { get; set; }
public MyViewModel()
{
this.Dispatcher = Dispatcher.CurrentDispatcher;
}
然后将以下内容添加到OnPropertyChanged
method:
if (this.Dispatcher != Dispatcher.CurrentDispatcher)
{
this.Dispatcher.Invoke(DispatcherPriority.Normal, new ThreadStart(delegate
{
OnPropertyChanged(propertyName);
}));
return;
}
但这没有用。有任何想法吗?
WPF 自动将属性更改封送到 UI 线程。但是,它不会封送集合更改,因此我怀疑您添加消息导致了失败。
您可以自己手动编组添加(请参见下面的示例),或者使用类似的东西这项技术 http://kentb.blogspot.com/2008/01/cross-thread-collection-binding-in-wpf.html我不久前写过博客。
手动编组:
public void backgroundWorker_ReportProgress(object sender, ReportProgressArgs e)
{
Dispatcher.Invoke(new Action<string>(AddMessage), e.Message);
OnPropertyChanged("Messages");
}
private void AddMessage(string message)
{
Dispatcher.VerifyAccess();
Messages.Add(message);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)