Exceptions thrown during Set operation on Property do not get caught

When I try to run a function inside the Set property clause, any exception thrown never gets into my global exception handler. I do not understand why this is happening. Here is my code (3 parts)

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 (where the global exception handler is used)

 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
source share
1 answer

As Bob Horn says, binding properties are not exploded if they come from the target element (TextBox), that is, from your view. Look in your output window, you will see a message something like this:

 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! 

But, try setting the same property from your ViewModel constructor , the application will certainly explode.

As a side note, this is not valid for all exceptions, try doing this -

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

This will certainly catch up with your global exception handler, since the application cannot be run in StackOverflow mode.

+3
source

Source: https://habr.com/ru/post/1437002/


All Articles