How to pass the UI Dispatcher to the ViewModel

前端 未结 16 568
独厮守ぢ
独厮守ぢ 2020-11-28 02:16

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

相关标签:
16条回答
  • 2020-11-28 02:48

    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
    
    0 讨论(0)
  • 2020-11-28 02:50

    No need to pass dispatcher when you can access application dispatcher using

    Dispatcher dis = Application.Current.Dispatcher 
    
    0 讨论(0)
  • 2020-11-28 02:52

    why would not you use

     System.Windows.Application.Current.Dispatcher.Invoke(
             (Action)(() => {ObservableCollectionMemeberOfVM.Add("xx"); } ));
    

    instead of keeping reference to GUI dispatcher.

    0 讨论(0)
  • 2020-11-28 02:52

    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.

    0 讨论(0)
提交回复
热议问题