How to pass the UI Dispatcher to the ViewModel

2020-01-25 04:05发布

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.

15条回答
在下西门庆
2楼-- · 2020-01-25 04:36

Maybe I am a bit late to this discussion, but I found 1 nice article https://msdn.microsoft.com/en-us/magazine/dn605875.aspx

There is 1 paragraph

Furthermore, all code outside the View layer (that is, the ViewModel and Model layers, services, and so on) should not depend on any type tied to a specific UI platform. Any direct use of Dispatcher (WPF/Xamarin/Windows Phone/Silverlight), CoreDispatcher (Windows Store), or ISynchronizeInvoke (Windows Forms) is a bad idea. (SynchronizationContext is marginally better, but barely.) For example, there’s a lot of code on the Internet that does some asynchronous work and then uses Dispatcher to update the UI; a more portable and less cumbersome solution is to use await for asynchronous work and update the UI without using Dispatcher.

Assume if you can use async/await properly, this is not an issue.

查看更多
家丑人穷心不美
3楼-- · 2020-01-25 04:39

Another common pattern (which is seeing much use now in the framework) is the SynchronizationContext.

It enables you to dispatch synchronously and asynchronously. You can also set the current SynchronizationContext on the current thread, meaning it is easily mocked. The DispatcherSynchronizationContext is used by WPF apps. Other implementations of the SynchronizationContext are used by WCF and WF4.

查看更多
神经病院院长
4楼-- · 2020-01-25 04:39

You don't need to pass the UI Dispatcher to the ViewModel. The UI Dispatcher is available from the current application singleton.

App.Current.MainWindow.Dispatcher

This will make your ViewModel dependent on the View. Depending on your application, that may or may not be fine.

查看更多
登录 后发表回答