本文介绍了异常在我的WPF应用程序中被吞噬。如何强制应用程序崩溃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是WPF的新手,我正在使用VS2010 beta2,.NET 4.0。

I am new to WPF, I am using VS2010 beta2, .NET 4.0.

抛出新的异常(test)在我的代码只是简单地吞下异常和应用程序不会崩溃。

Throw new Exception("test") in my code simply swallows exception and application does not crash.

这不是我期望的,如果未处理的异常发生,我希望应用程序崩溃。

This is not what I expect, I want the application to crash if unhandled exception occurs.

有没有一个简单的方法来实现这一点?

Is there a simple way to achieve this?

另外,应用程序。执行DispatcherUnhandledException AppDomain.UnhandledException 。这可能是因为所有代码都是作为数据绑定的一部分执行的(我使用MVVM模式,异常在ViewModel构造函数中抛出)。

Also, neither Application.DispatcherUnhandledException nor AppDomain.UnhandledException is executed. It is probably because all code is executed as part of the data binding (I am using MVVM pattern and exception is thrown in ViewModel constructor).

调试时可以查看输出窗口,找出有什么问题。但是似乎我很奇怪,应用程序只是忽略错误,使UI处于不正确的状态,并且不会崩溃。

While debugging I can look into Output window and find out what is wrong. But it seems to me odd, that application simply ignores error, leaves UI in incorrect state and does not crash.

编辑:

似乎在数据绑定时可能只会发生非关键的绑定异常。可能解决与绑定(例如连接到数据库)无直接关系的提取功能可能是解决方案。但是我不知道如何在MVVM中实现它。

It seems that maybe only non-critical binding exceptions should occur while databinding. Maybe extracting functionality which is not directly related to binding (for example connecting to database) out of the binding execution can be the solution. However I am not sure how to achieve it in MVVM.

简化示例:

XAML:

<DataTemplate DataType="{x:Type vm:ItemViewModel}">
    <vw:ItemControl />
</DataTemplate>

<ContentControl
 Content="{Binding Path=MyItem}"
 />

其中 MyItem 创建并返回 ItemViewModel 。问题是 ItemViewModel 的构造函数是作为数据绑定的一部分执行的,我不知道这是否是好的做法(此构造函数包含可能会失败的代码 - 例如,如果数据库

where MyItem creates and returns instance of ItemViewModel. Problem is that constructor of ItemViewModel is executed as part of the data binding and I am not sure if this is good practice (this constructor contains code which can fail - for example if database is not accessible).

推荐答案

您可以捕获在绑定和重新抛出它们时引发的异常 - 请参阅。

You can catch the exceptions raised during binding and rethrow them - see the answer to this question.

这篇关于异常在我的WPF应用程序中被吞噬。如何强制应用程序崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 00:27