如何在WPF中从ViewModel处理MessageBox.Show

Kar*_*hik 1 .net c# wpf dispatcher mvvm

我正在使用MVVM设计模式编写WPF应用程序.我想知道最好的(读"MVVM投诉")这样做的方式.另请注意,我的视图模型中的所有代码都不在UI线程上运行.目前我正在使用VM访问调度程序App.Current.Dispatcher,然后调用MessageBox.Show()它.

Til*_*lak 8

您应该创建以下服务

IMessageBoxService \\ Exposes Show(string Title, String Caption)
IDispatcherService \\ Exposes Dispatch(Action action), Register(Dispatcher)
Run Code Online (Sandbox Code Playgroud)

然后创建WPF特定实现为

MessageBoxService (or WPFMessageBoxService if you wish)
DispatcherService
Run Code Online (Sandbox Code Playgroud)

将这些注册到应用程序中使用的DI/IoC容器(例如Unity/MEF/Windsor)

对于依赖的View Model,通过构造函数传递服务

public MainViewModel(IMessageBoxService messageBoxService, IDispatcherService dispatcherService)
Run Code Online (Sandbox Code Playgroud)

现在,您可以使用messageBoxService/dispatcherService通过Dispatcher上的ViewModel调用消息框.

MessageBox示例