Diagnose WPF binding problems

One of the great things about WPF is that you can declare all your binding in XAML, and not have to write any code.

One of the most painful things about WPF is that you can declare all your binding in XAML, and not have to write any code.

Huh?

OK, so I am tired, but I’m not that tired, there was some sense in those first two paragraphs! XAML binding is extremely powerful, and allows you to do fab things without having to write a lot of C# (or VB.NET if you’re weird). However, when things don’t work as you expected, it’s very difficult to debug XAML. With C#, you can step through the code line by line, and see where it went wrong. You can’t do that with XAML.

However, you can get some clue as to what went wrong using System.Diagnostics.PresentationTraceSources. Never heard of it eh? Don’t feel bad, nor had I until just now.

If you add the following line to your namespace declarations at the top of any XAML file…

xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"

…and change the naughty binding to look like this…

Value="{Binding SystemNumber, diag:PresentationTraceSources.TraceLevel=High}"

…then when the binding is done at run time, you’ll get wads of gibberish in the Output window. Find the nearest person wearing a beanie hat with a propeller on top, and he’ll be able to explain it to you.

A bit more information

I later came across a blog post that shows how to get more debugging information, so you probably don’t need the geek in the beanie hat after all!

One Comment

  1. The Stupid Programmer said:

    Thanks, this was very useful!

    May 13, 2018
    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.