使用WPF和MVVM处理异常

3
我正在尝试使用WPF和MVVM模式构建应用程序。我有我的视图通过数据绑定从我的视图模型中填充。我希望有一个集中处理所有在应用程序中发生的异常的地方,这样我可以适当地通知用户并记录错误。
我知道Dispatcher.UnhandledException,但是它不起作用,因为在数据绑定期间引发的异常被记录到输出窗口中。因为我的视图绑定到我的视图模型,所以整个应用程序基本上是通过数据绑定控制的,因此我没有办法记录我的错误。
是否有一种通用的方式来处理数据绑定期间引发的异常,而无需在所有我的ViewModel公共方法周围放置try块?
示例视图:
<Window x:Class="Test.TestView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="TestView" Height="600" Width="800" 
    WindowStartupLocation="CenterScreen">
    <Window.Resources>
        <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
    </Window.Resources>
    <StackPanel VerticalAlignment="Center">
        <Label Visibility="{Binding DisplayLabel, Converter={StaticResource BooleanToVisibilityConverter}}">My Label</Label>
    </StackPanel>
</Window>

视图模型:

public class TestViewModel
{
    public bool DisplayLabel
    {
        get { throw new NotImplementedException(); }
    }
}

这是一个内部应用程序,因此我不想使用之前推荐的Wer。


请查看这个问题和答案:http://stackoverflow.com/questions/2171580/exceptions-are-swallowed-in-my-wpf-application-how-to-force-application-to-crash - Martin Pozor
1个回答

2
绑定实现旨在具有容错性,因此它捕获所有异常。您可以在绑定中激活以下属性:
  • ValidatesOnExceptions = true
  • NotifyOnValidationError = true
请参阅MSDN
这将导致在绑定的控件上引发附加的错误属性。但是,此基础结构旨在验证用户输入并显示验证消息。我不确定这是否是您正在做的事情。

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