MVVM异常处理 [英] MVVM Exception Handling

查看:180
本文介绍了MVVM异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我一直在尝试在MVVM的风格写一个WPF应用程序。如果一个异常被抛出(像文档打开时),我想显示一个MessageBox。很容易做到,但我的代码并不感到很正确,因为MessageBox.Show调用是在模型视图。我认为,这种事情应该是住在视图中,但我不应该把代码中的视图。

I have a WPF Application that I have been trying to write in the MVVM style. If an Exception is thrown (like when a document is opened), I would like to display a MessageBox. Easy to do, but my code doesn't feel quite right because the MessageBox.Show call is in the ModelView. I thought that sort of thing is supposed to live in the View, but I'm not supposed to put code in the View.

所以,真正的问题可以上下蒸馏为什么是显示在MVVM

So the question really can be distilled down to what is the suggested way to display a MessageBox in MVVM?

推荐答案

使用的服务的消息框建议的方式:<? / p>

Use a service:

public void SomeMethodInYourViewModel()
{
    try
    {
        DoSomethingDangerous();
    }
    catch (Exception ex)
    {
        ServiceLocator.Resolve<IMessageService>().ShowMessage(ex.Message);
    }
}

您现在已经从信息的呈现分离虚拟机。你甚至可以决定不使用标准可言,而且(丑陋的)消息框不会影响你的虚拟机。

You have now decoupled your VMs from the presentation of messages. You may even decide not to use the standard (ugly) message boxes at all and that won't affect your VMs.

这篇关于MVVM异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆