WPF: Snooping Attached Properties

01/09/2011

no comments

When developing WPF applications, Snoop is a wonderful tool that can let us see our visual tree at runtime, and find errors in data binding that are otherwise hard to track down in debugging. However, Snoop has an annoying limitation – it can’t show us data-bound Attached Properties. Let’s say we have the following XAML:

<Canvas>
   <Button Canvas.Left="{Binding Location.X}"
           Canvas.Top="{Binding Location.Y"}/>
</Canvas>

Snooping this application won’t show Canvas.Left and Canvas.Top among the Button’s properties, since they’re not a part of the Button object. If we have a bug in our binding, we won’t be able to find it.

So what do we do? We can set various TraceLevel attributes to save the binding errors to a log, but a quick workaround during debugging is to bind our data, in addition to the attached properties, to the element’s Tag property, a generic object that can bind to anything, and allow us to Snoop the binding – and find out any problems:

<Canvas>
   <Button Canvas.Left="{Binding Location.X}"
           Canvas.Top="{Binding Location.Y}"
           Tag="{Binding Location}" />
</Canvas>

This allowed me to find out, quickly, that my bug was simple – I had forgotten to make my Location property public, causing the binding to fail silently.

Add comment
facebook linkedin twitter email

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>