开发者

WPF MVVM Updating UI Bound properties from BackgroundWorker

Are there any potential issues with updating UI bound properties of the ViewModel from the Backgroundworker? I am trying to update the VM while开发者_StackOverflow it is bound to the UI, and potentially users might be typing in.. how does the the synchronization work here (I don't think I can use Lock statements from XAML).

Thanks in advance..


When updating scalar properties, you don't need to worry about doing it on the UI thread. The PropertyChanged event is automatically marshalled to the UI thread.

However, it won't work for collections that implement INotifyCollectionChanged. The CollectionChanged event won't be marshalled to the UI thread, and it will cause an exception. So if you modify a collection that is bound to an ItemsControl, you need to use Dispatcher.Invoke (or another synchronization mechanism) to do it on the UI thread. Another option is to use a specialized collection that takes care of marshalling the event to the correct thread. See this article for an example of such a collection.


In my experience with Silverlight, trying to do so will cause an exception anyway.

Basically you need to update the bound properties from the dispatcher thread, just as if you were modifying the UI directly.

In order to allow the ViewModel to do that without knowing about a real Dispatcher, I've found it useful to create an IDispatcher interface, then use a SameThreadDispatcher for tests and a SystemDispatcher (which delegates to the real thing) for production. You then pass the ViewModel the IDispatcher as a dependency.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜