[WPF] Convert binding errors into exceptions

If you’ve done a bit of XAML in your life, you may have seen that the WPF engine has a big tendency to swallow errors that happens in the bindings.

Ignored binding errors

To illustrate the issue, let’s start with a simple example:

<Label Content="{Binding UserName}" />

This simple binding might be buggy for the following reasons:

  1. The property name is misspelled (either in the view model or in the XAML) Example: public string Username { get { return "John"; } }

  2. The binding target is a field (it must be a property) Example: public string Username = "John";

  3. The property is private or internal (it must be public) Example: string Username { get { return "John"; } }

  4. The property getter throws an exception Example: public string UserName { get { throw new Exception(); } }

Unfortunately, in each case, WPF silently swallow the error and the <Label> ends up empty.

Listening to the TraceSource

WPF traces all the binding errors into PresentationTraceSources.DataBindingSource.

You can listen to these traces by overriding TraceListener:

class MyTraceListener : TraceListener
{
    public override void Write(string message)
    {
        Console.Write(message);
    }

    public override void WriteLine(string message)
    {
        Console.WriteLine(message);
    }
}

And then subscribe to the error traces:

var traceListener = new MyTraceListener();
PresentationTraceSources.DataBindingSource.Switch.Level = SourceLevels.Error;
PresentationTraceSources.DataBindingSource.Listeners.Add(traceListener);

A turnkey solution

I wrote a small library that uses this technique to turn binding errors into exceptions. It’s available in the following GitHub repository: https://github.com/bblanchon/WpfBindingErrors

Using this library is as simple as:

BindingExceptionThrower.Attach();

You just need to call this method once when the application starts, in App.OnStartup() for instance.

Exception displayed in Visual Studio's XAML editor

Please have a look at the README pages of the GitHub project to get more detail.

Unit tests

Converting binding errors to exceptions not only helps you debug you application at runtime, it’s also possible to use that feature to unit tests the bindings.

This is demonstrated in: https://github.com/bblanchon/WpfBindingErrors/tree/master/SampleWpfApplicationTests

Visual Studio's Test Explorer window

References