在我使用MVVM模式編寫的WPF應用程序中,我有一個後臺進程來完成這件事,但需要從中獲取狀態更新到用戶界面。我正在使用MVVM模式,所以我的ViewModel幾乎不知道向用戶展示模型的視圖(UI)。確保在MVVM WPF應用程序中的UI線程上調用OnPropertyChanged()
說我有以下的方法在我的視圖模型:
public void backgroundWorker_ReportProgress(object sender, ReportProgressArgs e)
{
this.Messages.Add(e.Message);
OnPropertyChanged("Messages");
}
我認爲,我有綁定到視圖模型的消息屬性(一個List<string>
)列表框。 OnPropertyChanged
通過調用PropertyChangedEventHandler
履行INotifyPropertyChanged
接口的作用。
我需要確保在UI線程上調用OnPropertyChanged
- 我該怎麼做?我已經試過如下:
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;
}
但這並沒有工作。有任何想法嗎?
也做到了,與另外一個小的修改 - 我改變了我的列表到ObservableCollction 和它的作品就像一個魅力。謝謝! –
2009-02-26 14:04:07