wpf mvvm threading.Timer and TimerCallback problems

℡╲_俬逩灬. 提交于 2019-12-25 00:42:26

问题


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:

  1. How to get around this problem?
  2. 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


回答1:


  1. Use the DispatcherTimer instead of the timer class you are using now, and make sure you create it on the UI thread.
  2. Probably with just an ObservableCollection your UI is not updated.



回答2:


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.



来源:https://stackoverflow.com/questions/5953087/wpf-mvvm-threading-timer-and-timercallback-problems

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!