Exception Handling with WPF and MVVM

I am trying to create an application using WPF and the MVVM pattern. I have my views populated from my ViewModel exclusively through data binding. I want to have a central place to handle all the exceptions that occur in my application, so I can notify the user and register the error accordingly.

I know about Dispatcher.UnhandledException, but this does not work, because the exception that occurs during data binding is written to the output windows. Since my view is data binding to my ViewModel, the entire application is largely controlled by data binding, so I have no way to log my errors.

Is there a way to generally handle exceptions that occur during data binding without having to put try blocks around all my public ViewModel?

Example:

<Window x:Class="Test.TestView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="TestView" Height="600" Width="800" 
    WindowStartupLocation="CenterScreen">
    <Window.Resources>
        <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
    </Window.Resources>
    <StackPanel VerticalAlignment="Center">
        <Label Visibility="{Binding DisplayLabel, Converter={StaticResource BooleanToVisibilityConverter}}">My Label</Label>
    </StackPanel>
</Window>

ViewModel:

public class TestViewModel
{
    public bool DisplayLabel
    {
        get { throw new NotImplementedException(); }
    }
}

This is an internal application, so I do not want to use Wer, as I saw earlier.

+3
source share
1 answer

The Binding implementation is designed for fault tolerance and therefore provides all exceptions. What you can do is activate the following properties in your bindings:

  • ValidatesOnExceptions = true
  • NotifyOnValidationError = true

See also MSDN .

This leads to an increase in the attached Error property on the associated control.

. , , .

+1

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


All Articles