What method do you use when debugging WPF events or bindings?
I tried to use breakpoint, but it seems like that something’s wrong with my XAML or behind the code that it never hits the breakpoint.
Is there a way to see when I click something in WPF, what event messages are popping up or not popping up to understand what went wrong?
In last 3 years of building WPF applications almost full-time I have collected a variety of reactive and preventative solutions to ensure that everything binds together properly.
Note:
I will give you a quick summary now and then post back in the morning (in 10 hours time) with code samples / screenshots.These are my most effective tools:
1) Create a converter that breaks the debugger when the
ConvertandConvertBackis executed. A quick and useful way to ensure that you have the values that you expect. I first learnt of this trick from Bea Stollnitz’s blog post.DebugConverter.cs
2) Create a
TraceListenerthat intercepts any errors. This is similar to what you see in the Visual Studio Output Window when you have a debugger attached. Using this method I can get the debugger to break when there is a exception thrown during a binding operation. This is better than settingPresentationTraceSources.TraceLevelas it applies to the entire application, not per-binding.DataBindingErrorLogger.cs
Usage
In the above,
ILoggeris an NLog log writer. I have a more complex version ofDefaultTraceListenerthat can report a full stack trace and actually throw exceptions however this will be enough to get you started (Jason Bock has an article on this extended implementation if you want to implement it yourself, although you will need code to actually to get it work).3) Use the Snoop WPF introspection tool to delve into your view and inspect your data objects. Using Snoop you can view the logical structure of your view and interactively change values to test different conditions.
Snoop WPF is absolutely essential to the iteration time of any WPF application. Among its many features, the Delve command allows you to drill down to your view/view model and interactively tweak values. To delve into a property, right-click to open the context menu and select Delve command; to go back up a level (un-delve?) there is a small button ^ in the top-right corner. For example, try delving into the
DataContextproperty.Edit: I can’t believe I just noticed this, however there is a Data Context tab in the Snoop WPF window.
4) Runtime checks on
INotifyPropertyChangedevents in#DEBUG. As the Data Binding system relies on being notified when properties have changed, it is important for your sanity that you are notifying that the correct property has changed. With a bit of reflection magic you canDebug.Assertwhen something is wrong.PropertyChangedHelper.cs
HTH,