I'm writing a WPF app using an MVVM approach. In my ViewModel, I have an ObservableCollection. Periodically, my app needs to check for new messages, and, if there are any, it needs to add them to the ObservableCollection.
If I try to add to the ObservableCollection in the DoWork, it doesn't work because of thread synchronization issues. It looks like the easiest way to get this to happen on the UI thread is to do a ReportProgress() and update the collection from there.
My question is: Philosophically and technically, is it ok to update the UI from the ReportProgress handler, even though "by the letter of the law" I'm not actually reporting progress.
Is there a more sound way to do this?
* EDIT: Code works using Dispatcher Timer *
ViewModel
class MyViewModel
{
public ObservableCollection<string> MyList { get; set; }
public MyViewModel()
{
MyList = new ObservableCollection<string>();
}
}
"teh codez" - just a sample, not my actual application code.
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();
}
This looks like it will work well for what I need, and doesn't give me additional baggage that I'm not going to use (e.g. cancel, workercompleted, etc.).