在属性的设置操作期间抛出的异常未被捕获。

5
当我尝试在属性的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));
    }
}

MainWindow.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>

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!");
    }
}

3
当程序运行时,请检查输出窗口。错误是否在那里显示?绑定属性不会崩溃,它们只是不会绑定。 - Bob Horn
1个回答

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!

但是,尝试在您的ViewModel构造函数中设置相同的属性,应用程序肯定会崩溃。

顺便说一下,这并不适用于所有异常情况,请尝试这样做 -

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

由于应用程序无法在 StackOverflow 模式下运行,因此这将绝对被您的全局异常处理程序捕获。


那么,绑定属性的Set块中发生的任何异常都将被视为绑定错误,是吗?这就可以解释这个问题了。我想我要么加一个try/catch语句,要么添加一个TextChanged事件处理程序。 - Kingamoon

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