views:

587

answers:

2

I am attempting to build an application using WPF and the MVVM pattern. I have my Views being populated from my ViewModel purely through databinding. I want to have a central place to handle all exceptions which occur in my application so I can notify the user and log the error appropriately.

I know about Dispatcher.UnhandledException but this does not do the job as exception that occur during databinding are logged to the output windows. Because my View is databound to my ViewModel the entire application is pretty much controlled via databinding so I have no way to log my errors.

Is there a way to generically handle the exceptions raised during databinding, without having to put try blocks around all my ViewModel public's?

Example View:

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

The ViewModel:

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

It is an internal application so I do not want to use Wer as I have seen previously recommended.

A: 

The Binding implementation is designed to be fault tolerant and so it catches all the exceptions. What you could do is to activate the following properties in your bindings:

  • ValidatesOnExceptions = true
  • NotifyOnValidationError = true

See also the MSDN.

This causes to raise the attached Error property on the bound control.

However, this infrastructure is designed for validating the user input and show validation messages. I’m not sure if this is what you are doing.

jbe