WPF: How can I debug WPF bindings, visually?
Early on Data-Binding in WPF can be kind of annoying, things aren’t binding correctly, UI isn’t being realized because of it. Searching Google for tips on how to debug those annoying data binding errors you probably found [this post] on Bea Stollnitz’s blog. Which has some great tips to help WPF newbies learn to debug those data binding errors. The important information to know is that when WPF has a data binding error, it logs it to the output console in Visual Studio. It also sends the information to a TraceSource that you can replace or add your own to redirect the same error elsewhere.
What’s wrong with that?
A GUI is a 2D (sometimes 3D) interface meaning that a simple text output isn’t always enough to tell you exactly what control is giving you the trouble. Sometimes the information provided makes it really obvious, other times it can be very difficult because really the only bits of information you have to go on are the control name (in my experience fewer and fewer names are being used because they’re no longer necessary), the control type and the type of the DataContext.
Applications can potentially dump a lot of information to the output view and you may miss it. You may also miss it because you’re just not watching the output view.
Possible Alternatives?
I wrote a new TraceSource that just threw the error into a MessageBox to put it in front of me so that I didn’t miss the error getting written to the output.
It was a better solution but there were still problems with it. The dialogs are modal and so you get tired of clicking OK every time they popup. It still didn’t make it any more obvious what control was causing the problem.
So, what if we could provide a visual alert that didn’t get in a users way?
I really wish there was a separate system in addition to the TraceSource that you could hook into specifically designed to report databinding errors. A system that was passed additional data, like which expression is actually logging the error.
Visual Solution
What if when a binding error occurred in addition to getting the debug output in visual studio you also saw visual indicators in the UI to alert you that a binding error had occurred, that way you are made aware an error has occurred and where in the UI you should look for the error in the XAML.
The first problem we need to solve to make this possible is to determine what elements have binding errors. We can achieve that with the following code block,
Once we found the expression with the error, we just need to add our adorner to the control that owns the expression.
To begin this search we just need to dispatch an operation inside a custom TraceListener, we just search from the top of any Forms or Windows in our application and work our way down.
If you want to see the full implementation check it out here: BindingErrorAdornerTraceListener.zip