假设我想向用户显示一些验证错误信息。在MVVM模式中,我可以有一个标签与我的viewmodel上的某个属性绑定。但是,如果我想要显示一个消息框并严格遵守MVVM模式,我的viewmodel将绑定到什么,以及如何触发创建/显示消息框?
假设我想向用户显示一些验证错误信息。在MVVM模式中,我可以有一个标签与我的viewmodel上的某个属性绑定。但是,如果我想要显示一个消息框并严格遵守MVVM模式,我的viewmodel将绑定到什么,以及如何触发创建/显示消息框?
定义一个接口 IMessageBoxService
,其内容如下:
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
。
在ViewModel中,使用IMessageBoxService.ShowMessage
来显示MessageBox。
ShowMessageCommand = new DelegateCommand (
() => messageBoxService.ShowMessage(message, header, MessageType.Information)
);
根据您的需求自定义 IMessageBoxService
接口,并选择一个更好的名称。
Delegate 'System.Predicate<object>' does not take 0 arguments
,出现在 () => messageBoxService.ShowMessage(message, header, MessageType.Information);
这一行。 - Mohammed Abrar Ahmed