How to pass the UI Dispatcher to the ViewModel

前端 未结 16 622
独厮守ぢ
独厮守ぢ 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:33

    I've find another (most simplest) way:

    Add to view model action that's should be call in Dispatcher:

    public class MyViewModel
    {
        public Action CallWithDispatcher;
    
        public void SomeMultithreadMethod()
        {
            if(CallWithDispatcher != null)
                CallWithDispatcher(() => DoSomethingMetod(SomeParameters));
        }
    }
    

    And add this action handler in view constructor:

        public View()
        {
            var model = new MyViewModel();
    
            DataContext = model;
            InitializeComponent();
    
            // Here 
            model.CallWithDispatcher += act => _taskbarIcon.Dispatcher
                .BeginInvoke(DispatcherPriority.Normal, act) ;
        }
    

    Now you haven't problem with testing, and it's easy to implement. I've add it to my site

提交回复
热议问题