Monday, November 24, 2014

Detecting Binding Errors in WPF

The binding engine in WPF is magical.  It makes possible the separation of the view from the view logic.  The MVVM pattern is dependent on this magical binding engine.  One not so great aspect of this is that binding errors fail silently in WPF.  There are several ways ways to get binding errors. For example, changing a property name and forgetting to update the Xaml binding expression.

WPF does log these data-binding errors to the output window.  The issue with that is it can sometimes be hard to find them amid all the other stuff being output by the debugger.  If you do manage to find one, it will look something like this....

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=DiamSlider'. BindingExpression:Path=Value; DataItem=null; target element is 'Slider' (Name='PipeDiamSlider'); target property is 'ToolTip' (type 'Object')

Another method for finding these errors is using a tool like Snoop or WPF Inspector. This works but it's tedious.

Recently I ran across a great simple solution to this issue.  Behind the scenes WPF is writing out errors to the PresentationTraceSources class.  This means that a simple trace listener can be created to show the output of the binding errors in a message box.  This trace listener is registered in the applications main window .xaml.cs.  This is a very simple idea, but it has been incredibly helpful in ridding our application of binding errors.

I discovered this method on in an article written by Michael Kuehl. Bea Stollnitz also has a great blog post that digs deeper into methods of detecting binding errors.

No comments:

Post a Comment