带有 MVVM 模式的 WPF MessageBox?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14297312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF MessageBox with MVVM pattern?
提问by ConditionRacer
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?
假设我想向用户显示一些验证错误。在 MVVM 模式中,我可以有一个绑定到我的视图模型上的某些属性的标签。但是如果我想在严格遵守 MVVM 模式的同时显示一个消息框呢?我的视图模型将绑定到什么,它如何触发要创建/显示的消息框?
回答by Tilak
Have an interface IMessageBoxServiceas:
有一个接口IMessageBoxService:
interface IMessageBoxService
{
bool ShowMessage(string text, string caption, MessageType messageType);
}
Create a WPFMessageBoxServiceclass:
创建一个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);
}
}
In your ViewModelaccept IMessageBoxService as a constructor parameter and inject WPFMessageBoxServiceusing DI/IoC.
在您ViewModel接受 IMessageBoxService 作为构造函数参数并WPFMessageBoxService使用 DI/IoC注入。
In the ViewModel, use IMessageBoxService.ShowMessageto show the MessageBox.
在 ViewModel 中,用于IMessageBoxService.ShowMessage显示 MessageBox。
ShowMessageCommand = new DelegateCommand (
() => messageBoxService.ShowMessage(message, header, MessageType.Information)
);
Customize IMessageBoxServiceinterface to your needs, and pick up a better name.
IMessageBoxService根据您的需要自定义界面,并取一个更好的名称。
回答by John Gerdsen
You could bind your messagebox control's visibility to the validation.
您可以将消息框控件的可见性绑定到验证。
You will need a Bool To Visibility converter for this.
为此,您将需要一个 Bool To Visibility 转换器。
See here for using the built in converter: Binding a Button's visibility to a bool value in ViewModel
有关使用内置转换器的信息,请参见此处: 将 Button 的可见性绑定到 ViewModel 中的 bool 值

