我正在使用MVVM方法編寫WPF應用程序。在我的ViewModel中,我有一個ObservableCollection。我的應用程序需要定期檢查新消息,如果有消息,它需要將它們添加到ObservableCollection中。可以使用BackgroundWorker的ReportProgress來做其他事情嗎?
如果我嘗試添加到DoWork中的ObservableCollection,由於線程同步問題,它不起作用。看起來在UI線程中發生這種情況的最簡單方法是執行ReportProgress()並從那裏更新集合。
我的問題是:哲學上和技術上,可以從ReportProgress處理程序更新UI,即使「通過法律信函」我並沒有實際報告進度。
有沒有更好的方法來做到這一點?
*編輯:代碼工作使用Dispatcher定時器*
視圖模型
class MyViewModel
{
public ObservableCollection<string> MyList { get; set; }
public MyViewModel()
{
MyList = new ObservableCollection<string>();
}
}
「德codez」 - 只是一個樣本,而不是我的實際應用程序代碼。
private void Window_Loaded(object sender, RoutedEventArgs e)
{
MyViewModel mvm = new MyViewModel();
this.DataContext = mvm;
DispatcherTimer mytimer = new DispatcherTimer();
mytimer.Interval = TimeSpan.FromSeconds(5.0);
mytimer.Tick += new EventHandler(mytimer_Tick);
mytimer.Start();
}
void mytimer_Tick(object sender, EventArgs e)
{
((DispatcherTimer)sender).Stop();
MyViewModel mvm = this.DataContext as MyViewModel;
mvm.MyList.Insert(0, DateTime.Now.ToLongTimeString());
((DispatcherTimer)sender).Start();
}
這看起來像它會爲我所需要的工作很好,不給我,我不會使用額外的行李(例如取消,workercompleted等)。
有趣。我喜歡。在我的信息中編輯代碼以顯示我最終結束的內容。 – Robaticus 2010-08-11 14:16:01