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
for WPF and Windows store apps use:-
System.Windows.Application.Current.Dispatcher.Invoke((Action)(() => {ObservableCollectionMemeberOfVM.Add("xx"); } ));
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:-
Deployment.Current.Dispatcher
No need to pass dispatcher when you can access application dispatcher using
Dispatcher dis = Application.Current.Dispatcher
why would not you use
System.Windows.Application.Current.Dispatcher.Invoke(
(Action)(() => {ObservableCollectionMemeberOfVM.Add("xx"); } ));
instead of keeping reference to GUI dispatcher.
As of MVVM Light 5.2, the library now includes a DispatcherHelper
class in GalaSoft.MvvmLight.Threading
namespace that exposes a function CheckBeginInvokeOnUI()
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 calling DispatcherHelper.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:
DispatcherHelper.CheckBeginInvokeOnUI(
() =>
{
//Your code here
});
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.