带有 MVVM 模式的 WPF MessageBox? [英] WPF MessageBox with MVVM pattern?

查看:39
本文介绍了带有 MVVM 模式的 WPF MessageBox?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想向用户显示一些验证错误.在 MVVM 模式中,我可以有一个绑定到我的视图模型上的某些属性的标签.但是如果我想在严格遵守 MVVM 模式的同时显示一个消息框呢?我的视图模型将绑定到什么,它将如何触发要创建/显示的消息框?

Say I want to display some validation error to the user. In the MVVM pattern, I could have a label that is bound to some property on my viewmodel. But what if I wanted to show a message box while strictly adhering to the MVVM pattern. What would my viewmodel bind to, and how would it trigger a message box to be created/displayed?

推荐答案

有一个接口 IMessageBoxService as:

interface IMessageBoxService
{
    bool ShowMessage(string text, string caption, MessageType messageType);
}

创建一个WPFMessageBoxService类:

using System.Windows;

class WPFMessageBoxService : IMessageBoxService
{
    bool ShowMessage(string text, string caption, MessageType messageType)
    {
        // TODO: Choose MessageBoxButton and MessageBoxImage based on MessageType received
        MessageBox.Show(text, caption, MessageBoxButton.OK, MessageBoxImage.Information);
    }
}

在您的 ViewModel 中接受 IMessageBoxService 作为构造函数参数并使用 DI/IoC 注入 WPFMessageBoxService.

In your ViewModel accept IMessageBoxService as a constructor parameter and inject WPFMessageBoxService using DI/IoC.

在 ViewModel 中,使用 IMessageBoxService.ShowMessage 来显示 MessageBox.

In the ViewModel, use IMessageBoxService.ShowMessage to show the MessageBox.

ShowMessageCommand = new DelegateCommand (
    () => messageBoxService.ShowMessage(message, header, MessageType.Information)
);

根据您的需要自定义 IMessageBoxService 接口,并取一个更好的名称.

Customize IMessageBoxService interface to your needs, and pick up a better name.

这篇关于带有 MVVM 模式的 WPF MessageBox?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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