I have a WPF application developed against the MVVM framework in which the ViewModel constructor set a Timer with a TimerCallback.
The TimerCallback retrieves an ObservableCollection and passes it to a field on the VM.
I have a CollectionViewSource which has its Source property set to the ObservableCollection. I am using a CollectionViewSource because I want to enable filtering on the Collection.
I have found that when the TimerCallback attempts to pass the ObservableCollection into the local field the Source property for the CollectionViewSource has an exception {"The calling thread cannot access this object because a different thread owns it."}.
I understand the exception but I have two problems:
- How to get around this problem?
- And more importantly why do I only get this issue when using a CollectionViewSource? If I remove the CollectionViewSource and make the ObservableCollection a public property then I get no such exception.
Any help appreciated! Thanks, Drammy
DispatcherTimer
instead of the timer class you are using now, and make sure you create it on the UI thread.ObservableCollection
your UI is not updated.To partially answer your question, any updates on ObservableCollection that might be observed by UI elements must be dispatched through the UI thread. When I wish to do this in MVVM, my strategy is to inject a SynchronizationContext into the constructor of the ViewModel that I initialize during my application startup. This gives me a View-framework-independent way to dispatch updates that must be synchronized with the View.