未捕获在属性中的Set操作期间抛出的异常

时间:2012-09-30 02:49:18

标签: c# wpf exception

当我尝试在Property的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!");
    }
}

1 个答案:

答案 0 :(得分:3)

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

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!

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

由于应用程序无法在StackOverflow模式下运行,因此肯定会遇到全局异常处理程序。