Are there any potential issues with updating UI bound properties of the ViewModel from the Backgroundworker? I am trying to update the VM while 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..
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 anIDispatcher
interface, then use aSameThreadDispatcher
for tests and aSystemDispatcher
(which delegates to the real thing) for production. You then pass the ViewModel theIDispatcher
as a dependency.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
. TheCollectionChanged
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 anItemsControl
, you need to useDispatcher.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.