使用MVVM模式的WPF MessageBox?

12

假设我想向用户显示一些验证错误信息。在MVVM模式中,我可以有一个标签与我的viewmodel上的某个属性绑定。但是,如果我想要显示一个消息框并严格遵守MVVM模式,我的viewmodel将绑定到什么,以及如何触发创建/显示消息框?


1
你的问题类似于这个问题:https://dev59.com/a3NA5IYBdhLWcg3wF5qO - Zack
2个回答

28

定义一个接口 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 接口,并选择一个更好的名称。


有趣且简单的解决方案!如何将MessageBox居中于您的窗口/控件中?在WPF中,通过回调接口通知视图并不常见。通常,视图通过绑定进行通知。但是该解决方案具有简单和直接的巨大优势! - jeromerg
@Tilak @Nautious 和 @Cameron MacFarland,你们能帮我解决这个错误吗?它说 Delegate 'System.Predicate<object>' does not take 0 arguments,出现在 () => messageBoxService.ShowMessage(message, header, MessageType.Information); 这一行。 - Mohammed Abrar Ahmed
当您将IMessageBoxService作为参数传递给视图模型构造函数时,您的意思是,例如创建一个WPFMessageBoxService实例并将该实例传递给视图模型构造函数?@Tilak - Willy
@Tilak,MessageType是什么?它来自System.Messaging程序集吗? - Willy
@Tilak,你能否解释一下DelegateCommand是什么,或者更新你的帖子来说明一下?我已经创建了一个委托,并尝试在我的视图模型中调用showMessage,但没有成功。另外,为什么要使用lambda来调用showMessage?直接使用messageBoxService.ShowMessage(...)不就可以了吗? - Willy
显示剩余4条评论

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接