UI Threading with ViewModels

.net, mvvm, wpf

Solution

One option here is to expose a SynchronizationContext usable from within the ViewModel. This is the mechanism the BackgroundWorker class uses to synchronize with the UI without introducing a dependency on WPF or Windows Forms, and allowing it to work with multiple technologies.

This would allow you to marshal back to the UI thread without taking a reference to the UI itself, including the Dispatcher.

Problem

- Collections that are bound in a WPF View must be updated on the UI thread. - ViewModel exposes a collection - Therefore when collection in the ViewModel is modified it must be done in the UI thread - Best practice is to keep ViewModels ignorant of View and presumably such details as Dispatcher. What is the cleanest way to resolve this while keeping view model testable?

Original source