问题描述
说我想显示一些验证错误给用户。在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模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!