[英]WPF MessageBox with MVVM pattern?
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.
在MVVM模式中,我可以有一个绑定到我的视图模型上某些属性的标签。 But what if I wanted to show a message box while strictly adhering to the MVVM pattern.
但是,如果我想在严格遵守MVVM模式的同时显示一个消息框,该怎么办? What would my viewmodel bind to, and how would it trigger a message box to be created/displayed?
我的视图模型将绑定到什么,它将如何触发创建/显示消息框?
Have an interface IMessageBoxService
as: 将接口
IMessageBoxService
为:
interface IMessageBoxService
{
bool ShowMessage(string text, string caption, MessageType messageType);
}
Create a WPFMessageBoxService
class: 创建一个
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 ViewModel
accept IMessageBoxService as a constructor parameter and inject WPFMessageBoxService
using DI/IoC. 在您的
ViewModel
接受IMessageBoxService作为构造函数参数,并使用DI / IoC注入WPFMessageBoxService
。
In the ViewModel, use IMessageBoxService.ShowMessage
to show the MessageBox. 在ViewModel中,使用
IMessageBoxService.ShowMessage
来显示MessageBox。
ShowMessageCommand = new DelegateCommand (
() => messageBoxService.ShowMessage(message, header, MessageType.Information)
);
Customize IMessageBoxService
interface to your needs, and pick up a better name. 根据您的需求自定义
IMessageBoxService
接口,并选择一个更好的名称。
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 请参阅此处以使用内置转换器: 在ViewModel中将Button的可见性绑定到bool值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.