属性中的 Set 操作期间引发的异常不会被捕获

Kin*_*oon 5 c# wpf exception

当我尝试在属性的 Set 子句内运行函数时,我的全局异常处理程序永远不会捕获可能出现的任何异常。我不明白为什么会发生这种情况。这是我的代码(3部分)

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModel_();
    }
}

public class ViewModel_ : INotifyPropertyChanged
{
    public ViewModel_()
    {
    }

    public string Texting
    {
        get { return _Texting; }
        set
        {
            _Texting = value;
            OnPropertyChanged("Texting");
            throw new Exception("BAM!");
        }
    }
    private string _Texting;


    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }
}
Run Code Online (Sandbox Code Playgroud)

主窗口.xaml

<Window x:Class="TestExceptionHandling.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <TextBox Text="{Binding Path=Texting,
        UpdateSourceTrigger=PropertyChanged}" />
</Grid>
Run Code Online (Sandbox Code Playgroud)

App.xaml.cs(全局异常处理程序所在的位置)

public partial class App : Application
{
    public App()
    {
        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
    }

    void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        MessageBox.Show("SOMETHING IS WRONG!");
    }
}
Run Code Online (Sandbox Code Playgroud)

Roh*_*ats 3

正如 所说Bob Horn,如果绑定属性来自目标元素(TextBox)(即来自您的视图),则绑定属性不会爆炸。查看你的输出窗口,你会看到类似这样的消息 -

A first chance exception of type 'System.Exception' occurred in WpfApplication4.exe
An exception of type 'System.Exception' occurred in WpfApplication4.exe but was not handled in user code
System.Windows.Data Error: 8 : Cannot save value from target back to source. BindingExpression:Path=Name; DataItem='VM' (HashCode=28331431); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String') Exception:'System.Exception: BAM!
Run Code Online (Sandbox Code Playgroud)

但是,try setting the same property from your ViewModel's constructor应用程序肯定会崩溃。

作为旁注,这不适用于所有异常,请尝试这样做 -

public string Texting
{
    get { return _Texting; }
    set
    {
        _Texting = value;
        OnPropertyChanged("Texting");
        throw new StackOverflowException("BAM!");
    }
}
Run Code Online (Sandbox Code Playgroud)

这肯定会被您的全局异常处理程序捕获,因为应用程序无法在StackOverflow模式下运行。