Wednesday, March 30, 2011

How can I debug WPF bindings?

Data Binding can be tricky to debug. In this post, I will share the techniques I use to debug WPF bindings, including the new debugging improvements we implemented in the latest 3.5 release. I will discuss the following four techniques:

Scanning Visual Studio’s Output window for errors.
Using Trace Sources for maximum control.
Using the new property introduced in WPF 3.5 PresentationTraceSources.TraceLevel.
Adding a breakpoint to a Converter.

The DataContext of this app is set to a new instance of Star, which is a class that contains two properties: Picture and Caption. Picture is of type BitmapImage and contains an image of the sun, which I included in the project. Caption is a string property that takes a while to be initialized (more details about this later).
Output Window
In the XAML of this application, I have an Image whose Source is data bound to an incorrect property name. This is a simple scenario that causes a Binding to fail.

    <Image Source="{Binding Path=PictureWrong}" Width="300" Height="300" Grid.Row="0"/>
Every time a Binding fails, the binding engine prints an informative message in the Output window of Visual Studio. In this case, I get the following message:
    System.Windows.Data Error: 35 : BindingExpression path error: ‘PictureWrong’ property not found on ‘object’ ”Star’ (HashCode=49535530)’. BindingExpression:Path=PictureWrong; DataItem=’Star’ (HashCode=49535530); target element is ‘Image’ (Name=”); target property is ‘Source’ (type ‘ImageSource’)

This message should give you enough information to quickly figure out the mistake in the property name.

Advantage of this technique:
It is very easy to look at the Output window, and in most cases it’s sufficient. It should be the first approach you consider when you have a problem with your bindings.

Disadvantage of this technique:
Most real world applications print so much information to the Output window that it may be hard to find the error you’re looking for.

Trace Sources
The Trace Sources solution was already around in WPF 3.0. It adds a lot more flexibility to the previous solution by allowing you to control the level of detail you care about, where you want that messages to be printed and the WPF feature you want to debug.
The Trace Sources solution relies on a config file for the configuration of its behavior – the App.config file. Here is a portion of the contents of that file:

    <configuration>
         <system.diagnostics>
            <sources>
     
            <source name="System.Windows.Data" switchName="SourceSwitch" >
                <listeners>
                    <add name="textListener" />
                </listeners>
            </source>
            …
         
            <switches>
                …
                <add name="SourceSwitch" value="All" />
            </switches>
        
            <sharedListeners>

Read more: Bea Stollnitz