Fixing Data Binding Problems in WPF/Silverlight
The data binding in WPF is simply amazing. Since Visual Basic 3, Microsoft has been trying to find that magic combination of flexibility, robustness, and ease of use. And while WPF isn’t perfect, it has come far closer than anything before it. Unfortunately its failure model is a double-edged sword. Instead of throwing application-crashing exceptions, binding errors are quietly written to the trace listener. This can make finding the root cause incredibly hard.
The primary document on data binding in WPF is the simply titled article Data Binding Overview. While being a must-read for any WPF or Silverlight developer, it offers nearly nothing when it comes to debugging and troubleshooting. The entire section is literally just one sentence.
You can set the attached property PresentationTraceSources.TraceLevel on a binding-related object to receive information about the status of a specific binding.
Karl Shifflett offers some instruction on reading that data binding traces, but rest of his advice consists of obvious things to check like whether or not the DataContext contains the right object. And since Silverlight often runs outside of the IDE, even that isn’t always an option.
Fortunately there are a couple of third-party tools to makes things a bit easier. Cory Plotts’ Snoop can attach to any .NET 3.5 or 4.0 WPF application. Once loaded, it gives you detailed information on the control trees, where properties are getting their value from, and any data binding errors. Snoop 2.6 is available on CodePlex under the Microsoft Public License.
Another tool is Karl Shifflett’s Glimpse. This tool cannot be attached to a Silverlight application; it must be compiled into it. Once started, it will alert the user to unhandled application and data-binding exceptions via a floating window. Glimpse for Silverlight can be downloaded from Karl’s personal blog.
An often cited technique is to add a dummy value converter and then set a break point within it. Marlon Grech goes one step further by showing how to write a Debug Converter. By hard-coding a break statement in the code he eliminates the need to manually set a break point.
Ian Culling, Andy Powell & Lee Cunningham Dec 11, 2013