显示从视图模型一个消息框违反MVVM的 - 如何避免? [英] Showing a message box from the ViewModel is a violation of MVVM - how to avoid?
问题描述
在观看有关MVVM视频Pluralsight有这样一种情况:MVVM模式得到了侵犯,但这样做表现出的不正确的方法:
While watching a video about MVVM on Pluralsight there was a situation where the MVVM pattern got violated but no correct way of doing it was shown:
- 的观点有使用ICommand的触发在视图模型的处理程序的按钮。
- 的处理程序正确地传达执行到存储库的实现。
- 的具体实现称为Web服务方法的存储库
不过:如果Web服务调用失败,视图模型将带来高达,通知有关错误的用户的消息框。
作为视图模型是视图的抽象,它不应该直接创建UI,但什么是100%干净的方式得到呈现给用户的消息框?
However: if the webservice call failed, the ViewModel would bring up a message box that informs the user about the error. As the ViewModel is an abstraction of the View, it should not directly create UI, but what is the 100% clean way to get that message box presented to the user?
推荐答案
创建服务:
interface IDialogService
{
void ShowMessageBox(string message);
}
实现它:
Implement it:
class DialogService : IDialogService
{
public void ShowMessageBox(string message)
{
MessageBox.Show(); // ...
}
}
使用依赖注入:
class ViewModel
{
[Import] // This is MEF-specific sample
private readonly IDialogService dialogService;
}
或服务的位置:
class ViewModel
{
private AnyCommandExecute()
{
// This is MEF-specific sample
var dialogService = container.GetExportedValue<IDialogService>();
}
}
要获得具体的 IDialogService
在您的视图模型,然后调用从视图模型所获得的实施
to obtain a concrete IDialogService
in your view model, then call the obtained implementation from ViewModel.
同样的方法适用于任何其他类似的情况:显示打开/保存对话框,显示在对话框中输入自定义视图模式。
The same approach is applicable for any other similar cases: show open/save dialog, show your custom view model in dialog.
这篇关于显示从视图模型一个消息框违反MVVM的 - 如何避免?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!