显示来自 ViewModel 的消息框违反了 MVVM - 如何避免? [英] Showing a message box from the ViewModel is a violation of MVVM - how to avoid?

查看:19
本文介绍了显示来自 ViewModel 的消息框违反了 MVVM - 如何避免?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Pluralsight 上观看有关 MVVM 的视频时,出现了违反 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 触发 ViewModel 中的处理程序.
  • 处理程序正确地将执行中继到存储库实现.
  • 存储库的具体实现称为 Web 服务方法.

然而:如果 webservice 调用失败,ViewModel 会弹出一个消息框,通知用户错误.由于 ViewModel 是 View 的抽象,它不应该直接创建 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);
}

实施:

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,然后从ViewModel调用获得的实现.

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.

这篇关于显示来自 ViewModel 的消息框违反了 MVVM - 如何避免?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆