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

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

问题描述

说我想显示一些验证错误给用户。在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

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

创建 WPFMessageBoxService

class WPFMessageBoxService:IMessageBoxService
{
  bool ShowMessage(string text, string caption, MessageType messageType)
  {
     System.Windows.MessageBox.Show(text,caption); // messageBoxIcon is created based on MessageType // Removed windows forms dependency.
  }

}

在你的视图模型接受IMessageBoxService作为构造函数的参数和使用DI注入 WPFMessageBoxService / IoC的。

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

在视图模型,使用 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.

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

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