Further demystification of dependency properties

In my previous blog post we examined how a dependency property can be given a value by multiple entities, but its actual value is resolved by the WPF property system based on a set of well-defined rules.  In this post we will dig deeper into how this works, by examining how a dependency property in a simple demo application gets its value.  Understanding how this value resolution process works is critical for those of us who want to do serious WPF programming, so I think it’s important to study this topic in great depth.

The demo application, which is available to download at the end of this post, contains a TextBlock whose Text property is set in various ways.  We can experiment with how the Text dependency property’s value is determined by checking/unchecking some CheckBoxs and putting the mouse cursor over the TextBlock (which activates a Trigger).

This is what the demo app looks like when you first start it:

Initial UI

The TextBlock whose Text property we are interested in is green.  In the screenshot above, it is displaying the string which was assigned to its Text property in the code-behind.

If you uncheck the upper CheckBox, the following method is executed:

ClearValue in action

The UI now looks like this:

Style-supplied value

Here is the Style which provides the TextBlock’s Text property with its new value:

Style applied to the TextBlock

If you were to now put the mouse cursor over the TextBlock, the Style’s sole trigger would be activated.  At that point the Setter in the Style’s Trigger would provide the property’s effective value. The UI would look like this:

Trigger-supplied value

If you were to then uncheck the bottom CheckBox, the Text property’s default value (an empty string) would be used. At that point the TextBlock is not displayed because a TextBlock naturally wants to only be big enough to display its text.  In this situation the UI looks like this:

The Text property’s default value is being used here

This demonstrates how a dependency property’s value is contingent on the values provided to it by external entities, such as a Style or default value.  In this example, when the Text property has a local value assigned to it, that value trumps those provided by the Style and the property’s default value.  When the Style’s trigger is active, its value takes precedence over the Style’s Setter and the property’s default value. 

You can download the demo project here.  Be sure to change the file’s extension from .DOC to .ZIP and then decompress it.

3 Responses to Further demystification of dependency properties

  1. […] my next post we take a look at an example of the DP value resolution process being used, to gain a clearer […]

  2. Fluxtah says:

    Cheers, that was useful🙂

  3. Spartan says:

    Thanks for the post, nice and clear!

%d bloggers like this: