【问题标题】:Correct implementation of WPF custom MessageBox using MVVM pattern使用 MVVM 模式正确实现 WPF 自定义 MessageBox
【发布时间】:2014-12-13 22:53:41
【问题描述】:

我对 WPF 很陌生,我必须按照 MVVM 模式实现自定义消息框,但不使用任何 MVVM 帮助程序库。此消息框将用于提供有关应用程序中发生的意外错误的信息 - 一般消息 + 详细信息中的堆栈跟踪。 我正在为此处理 DispatcherUnhandledException 事件,并在该事件的处理程序中使用此自定义消息框。

void Current_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
    {
        CustomMessageBoxViewModel messageBox = new CustomMessageBoxViewModel();
        messageBox.ShowMessage(e.Exception.Message, e.Exception.StackTrace);
        CustomMessageBoxWindow messageBoxWindow = new CustomMessageBoxWindow();
        messageBoxWindow.DataContext = messageBox;
        messageBoxWindow.Show();

        e.Handled = true;
    }

您能否告诉我这是否是对 MVVM 模式的正确使用,如果不是,我可以做些什么来解决它?

【问题讨论】:

    标签: c# wpf mvvm


    【解决方案1】:

    您的示例是正确使用 MVVM 模式,因为您有一个单独的 ViewModel,我假设您绑定到该 ViewModel 并且不知道 View。

    您可能可以通过将 ShowMessage 函数(我猜它实际上不显示消息)替换并设置它来简化 ViewModel。

    您不使用 ShowDialog 的任何原因?如果某些事情持续出错,您最终可能会在屏幕上看到很多异常对话框。

    void Current_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
    {
        CustomMessageBoxViewModel messageBox = new CustomMessageBoxViewModel();
        messageBox.Sender = sender;
        messageBox.Exception = e.Exception;
        CustomMessageBoxWindow messageBoxWindow = new CustomMessageBoxWindow();
        messageBoxWindow.DataContext = messageBox;
        messageBoxWindow.ShowDialog();
    
        e.Handled = true;
    }
    

    【讨论】:

    • 感谢您的回复,我已根据您的建议更正了我的代码,它确实简化了我的视图模型。另外,我不知道 Show 和 ShowDialog 之间的区别,但现在我也将 Show() 更改为 ShowDialog()。
    • 如果发生未处理的异常,我正在考虑终止应用程序,但我很不确定。
    • 终止应用程序是个好主意,因为未处理的异常可能会损坏您的数据。在此之前,您至少应该记录异常详细信息,如果不只是将其显示给用户以复制/粘贴并将其发回给您。查看codeproject.com/Tips/469452/WPF-ExceptionViewer 上的 ExceptionViewer 如何获取任何异常的内部细节(IIRC 代码在少数地方存在错误 - NullReferenceException),您最终可能会为您的应用用户制作此类查看器的 MVVM 版本。
    【解决方案2】:

    我将创建一个实现 IDialogService 的 DialogService 类。此类/接口应包含您认为适合所需对话框的任何方法。

    我也会使用像 Unity 这样的依赖注入器,所以在我的单元测试中我可以模拟 IDialogService 并且不会弹出 MessageBox 窗口。另一种方法是将实际的 UI 代码放在受保护的虚拟方法中,并让您的单元测试使用 IDialogService 来替换 MessageBox 调用。

    所以在你的情况下,我只会调用 IDialogService.DisplayError(Exception ex) 之类的东西。

    【讨论】:

    • 感谢您的回复!我正在使用依赖注入器,它是 Unity(这是我被允许使用的),我还使用 IDialogService 来处理随机消息(为此我使用普通的 MessageBox)。将这个小逻辑也移到那里可能是个好主意。
    猜你喜欢
    • 2017-12-06
    • 2012-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    相关资源
    最近更新 更多