4

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

主窗口.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));
    }
}

主窗口.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!");
    }
}
4

1 回答 1

3

如前所述Bob Horn,绑定属性不会爆炸,如果它们来自目标元素(文本框),即来自您的视图。查看您的输出窗口,您将看到类似这样的消息 -

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模式下运行。

于 2012-09-30T08:14:35.563 回答