I'm supposed to be able to access the Dispatcher that belongs to the View I need to pass it to the ViewModel. But the View should not know anything about the ViewModel, so how do you pass it? Introduce an interface or instead of passing it to the instances create a global dispatcher singleton that will be written by the View? How do you solve this in your MVVM applications and frameworks?
EDIT: Note that since my ViewModels might be created in background threads I can't just do Dispatcher.Current
in the constructor of the ViewModel.
I've find another (most simplest) way:
Add to view model action that's should be call in Dispatcher:
And add this action handler in view constructor:
Now you haven't problem with testing, and it's easy to implement. I've add it to my site
Some of my WPF projects I have faced the same situation. In my MainViewModel (Singleton instance), I got my CreateInstance() static method takes the dispatcher. And the create instance gets called from the View so that I can pass the Dispatcher from there. And the ViewModel test module calls CreateInstance() parameterless.
But in a complex multithread scenario it is always good to have an interface implementation on the View side so as to get the proper Dispatcher of the current Window.
As of MVVM Light 5.2, the library now includes a
DispatcherHelper
class inGalaSoft.MvvmLight.Threading
namespace that exposes a functionCheckBeginInvokeOnUI()
that accepts a delegate and runs it on the UI thread. Comes in very handy if your ViewModel is running some worker threads which affect VM properties to which your UI elements are bound.DispatcherHelper
must be initialized by callingDispatcherHelper.Initialize()
at an early stage in the life of your application (e.g.App_Startup
). You can then run any delegate (or lambda) using the following call:Note that the class is defined in
GalaSoft.MvvmLight.Platform
library which is not referenced by default when you add it through NuGet. You must manually add a reference to this lib.why would not you use
instead of keeping reference to GUI dispatcher.
for WPF and Windows store apps use:-
keeping reference to GUI dispatcher is not really the right way.
if that doesn't work (such as in case of windows phone 8 apps) then use:-
I have abstracted the Dispatcher using an interface IContext:
This has the advantage that you can unit-test your ViewModels more easily.
I inject the interface into my ViewModels using the MEF (Managed Extensibility Framework). Another possibility would be a constructor argument. However, I like the injection using MEF more.
Update (example from pastebin link in comments):