gpt4 book ai didi

c# - 处理来自绑定(bind) MVVM 属性的未捕获异常

转载 作者:行者123 更新时间:2023-12-03 10:15:33 25 4
gpt4 key购买 nike

我正在尝试处理我的 WPF 应用程序中的所有未捕获的异常。

我创建了一个虚拟项目并将 App.xaml.cs 更改为如下所示

public partial class App : Application
{
public App()
{
this.Dispatcher.UnhandledException += (sender, args) =>
{
Console.WriteLine("Test1");
};

AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
{
Console.WriteLine("Test2");
};

Application.Current.DispatcherUnhandledException += (sender, args) =>
{
Console.WriteLine("Test3");
};

AppDomain.CurrentDomain.FirstChanceException += (sender, args) =>
{
Console.WriteLine("Test4");
};
}
}

我还有这个 ViewModel 和名为 TestProp 的属性,我已将其绑定(bind)到 XAML 中的 TextBox.Text:
public class TestViewModel
{
private string testProp;

public string TestProp
{
get => testProp;
set
{
testProp = value;

// RAISE EXCEPTION IN PROPERTY SETTER
throw new Exception("Test Exception");
}
}
}

在 View 中更改该属性将引发异常,但是 App.xaml.cs 中的任何事件都不会被触发,除了 FirstChanceException。

FirstChanceException 的问题是,即使我在代码中处理异常,它也会被引发。

我只是希望全局处理所有未处理的异常,这样我就可以记录错误并显示错误对话框,而不必用 try/catch 包装每个 getter/setter。

这可能吗?谢谢

最佳答案

是的,这是可能的。您必须实现 App.DispatcherUnhandledException 事件。
点评 this文章向您展示如何实现它。

==============================================

更新 1:
是的,正如@Maciek Świszczowski 在评论中提到的那样,您已经在您的初始代码中实现了它,我没有注意到它是我的错误。

您遇到的问题是,在用作 View 模型的类中引发异常会进入 WPF 验证系统。此功能称为“数据对象验证”,异常不会出现在 App.DispatcherUnhandledException 事件中,而是出现在 WPF 验证系统中。

在 App.DispatcherUnhandledException 中全局处理数据对象通知中引发的异常的一种方法是让它们冒泡到应用程序的顶部。在代码中,可以通过将 ExceptionValidationRule 类添加到属性的绑定(bind)中,并在 Validation.error 附加事件中抛出异常来完成,如下所示:

<Window
x:Class="WpfApp10.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApp10"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="800" Height="450"
d:DataContext="{d:DesignInstance Type=local:TestViewModel}"
mc:Ignorable="d">
<StackPanel>
<TextBox Validation.Error="Validation_OnError">
<TextBox.Text>
<Binding NotifyOnValidationError="True" Path="TestProp" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<ExceptionValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
</StackPanel>
</Window>

在后面的代码中:
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
var vm = new TestViewModel();
this.DataContext = vm;
//throw new Exception("Test2 Exception");
}

private void Validation_OnError(object sender, ValidationErrorEventArgs e) {
throw e.Error.Exception;
}
}

我测试了代码 here

关于c# - 处理来自绑定(bind) MVVM 属性的未捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61349141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com