Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UI Threading with ViewModels

Tags:

.net

mvvm

wpf

  • 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?

like image 368
Jack Ukleja Avatar asked Jan 21 '10 02:01

Jack Ukleja


1 Answers

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.

like image 83
Reed Copsey Avatar answered Oct 13 '22 09:10

Reed Copsey