Bookmark and Share Share...    Subscribe to this feed Feed   About Christian Moser  


Dependency Properties

Introduction

Value resolution strategy

The magic behind it

How to create a DepdencyProperty

Readonly DependencyProperties

Attached DependencyProperties

Listen to dependency property changes

How to clear a local value

Introduction

When you begin to develop appliations with WPF, you will soon stumble across DependencyProperties. They look quite similar to normal .NET properties, but the concept behind is much more complex and powerful.

The main difference is, that the value of a normal .NET property is read directly from a private member in your class, whereas the value of a DependencyProperty is resolved dynamically when calling the GetValue() method that is inherited from DependencyObject.

When you set a value of a dependency property it is not stored in a field of your object, but in a dictionary of keys and values provided by the base class DependencyObject. The key of an entry is the name of the property and the value is the value you want to set.

The advantages of dependency properties are

  • Reduced memory footprint
    It's a huge dissipation to store a field for each property when you think that over 90% of the properties of a UI control typically stay at its initial values. Dependency properties solve these problems by only store modified properties in the instance. The default values are stored once within the dependency property.

  • Value inheritance
    When you access a dependency property the value is resolved by using a value resolution strategy. If no local value is set, the dependency property navigates up the logical tree until it finds a value. When you set the FontSize on the root element it applies to all textblocks below except you override the value.

  • Change notification
    Dependency properties have a built-in change notification mechanism. By registering a callback in the property metadata you get notified, when the value of the property has been changed. This is also used by the databinding.

Value resolution strategy

Every time you access a dependency property, it internally resolves the value by following the precedence from high to low. It checks if a local value is available, if not if a custom style trigger is active,... and continues until it founds a value. At last the default value is always available.

The magic behind it

Each WPF control registers a set of DependencyProperties to the static DependencyProperty class. Each of them consists of a key - that must be unique per type - and a metadata that contain callbacks and a default value.

All types that want to use DependencyProperties must derive from DependencyObject. This baseclass defines a key, value dictionary that contains local values of dependency properties. The key of an entry is the key defined with the dependency property.
When you access a dependency property over its .NET property wrapper, it internally calls GetValue(DependencyProperty) to access the value. This method resolves the value by using a value resolution strategy that is explained in detail below. If a local value is available, it reads it directly from the dictionary. If no value is set if goes up the logical tree and searches for an inherited value. If no value is found it takes the default value defined in the property metadata. This sequence is a bit simplified, but it shows the main concept.

How to create a DependencyProperty

To create a DependencyProperty, add a static field of type DepdencyProperty to your type and call DependencyProperty.Register() to create an instance of a dependency property. The name of the DependendyProperty must always end with ...Property. This is a naming convention in WPF.

To make it accessable as a normal .NET property you need to add a property wrapper. This wrapper does nothing else than internally getting and setting the value by using the GetValue() and SetValue() Methods inherited from DependencyObject and passing the DependencyProperty as key.

Important: Do not add any logic to these properties, because they are only called when you set the property from code. If you set the property from XAML the SetValue() method is called directly.

If you are using Visual Studio, you can type propdp and hit 2x tab to create a dependency property.

 
// Dependency Property
public static readonly DependencyProperty CurrentTimeProperty = 
     DependencyProperty.Register( "CurrentTime", typeof(DateTime),
     typeof(MyClockControl), new FrameworkPropertyMetadata(DateTime.Now));
 
// .NET Property wrapper
public DateTime CurrentTime
{
    get { return (DateTime)GetValue(CurrentTimeProperty); }
    set { SetValue(CurrentTimeProperty, value); }
}
 
 

Each DependencyProperty provides callbacks for change notification, value coercion and validation. These callbacks are registered on the dependency property.

 
new FrameworkPropertyMetadata( DateTime.Now, 
                       OnCurrentTimePropertyChanged, 
                       OnCoerceCurrentTimeProperty ),
                       OnValidateCurrentTimeProperty );
 
 

Value Changed Callback

The change notification callback is a static method, that is called everytime when the value of the TimeProperty changes. The new value is passed in the EventArgs, the object on which the value changed is passed as the source.

 
private static void OnCurrentTimePropertyChanged(DependencyObject source, 
        DependencyPropertyChangedEventArgs e)
{
    MyClockControl control = source as MyClockControl;
    DateTime time = (DateTime)e.NewValue;
    // Put some update logic here...
}
 
 

Coerce Value Callback

The coerce callback allows you to adjust the value if its outside the boundaries without throwing an exception. A good example is a progress bar with a Value set below the Minimum or above the Maximum. In this case we can coerce the value within the allowed boundaries. In the following example we limit the time to be in the past.

 
private static object OnCoerceTimeProperty( DependencyObject sender, object data )
{
    if ((DateTime)data > DateTime.Now )
    {
        data = DateTime.Now;
    }
    return data;
}
 
 

Validation Callback

In the validate callback you check if the set value is valid. If you return false, an ArgumentException will be thrown. In our example demand, that the data is an instance of a DateTime.

 
private static bool OnValidateTimeProperty(object data)
{
    return data is DateTime;
}
 
 

Readonly DependencyProperties

Some dependency property of WPF controls are readonly. They are often used to report the state of a control, like the IsMouseOver property. Is does not make sense to provide a setter for this value.

Maybe you ask yourself, why not just use a normal .NET property? One important reason is that you cannot set triggers on normal .NET propeties.

Creating a read only property is similar to creating a regular DependencyProperty. Instead of calling DependencyProperty.Register() you call DependencyProperty.RegisterReadonly(). This returns you a DependencyPropertyKey. This key should be stored in a private or protected static readonly field of your class. The key gives you access to set the value from within your class and use it like a normal dependency property.

Second thing to do is registering a public dependency property that is assigned to DependencyPropertyKey.DependencyProperty. This property is the readonly property that can be accessed from external.


 
// Register the private key to set the value
private static readonly DependencyPropertyKey IsMouseOverPropertyKey = 
      DependencyProperty.RegisterReadOnly("IsMouseOver", 
      typeof(bool), typeof(MyClass), 
      new FrameworkPropertyMetadata(false));
 
// Register the public property to get the value
public static readonly DependencyProperty IsMouseoverProperty = 
      IsMouseOverPropertyKey.DependencyProperty;    
 
// .NET Property wrapper
public int IsMouseOver
{
   get { return (bool)GetValue(IsMouseoverProperty); }
   private set { SetValue(IsMouseOverPropertyKey, value); }
}
 
 

Attached Properties

Attached properties are a special kind of DependencyProperties. They allow you to attach a value to an object that does not know anything about this value.

A good example for this concept are layout panels. Each layout panel needs different data to align its child elements. The Canvas needs Top and Left, The DockPanel needs Dock, etc. Since you can write your own layout panel, the list is infinite. So you see, it's not possible to have all those properties on all WPF controls.

The solution are attached properties. They are defined by the control that needs the data from another control in a specific context. For example an element that is aligned by a parent layout panel.

To set the value of an attached property, add an attribute in XAML with a prefix of the element that provides the attached property. To set the the Canvas.Top and Canvas.Left property of a button aligned within a Canvas panel, you write it like this:

<Canvas>
    <Button Canvas.Top="20" Canvas.Left="20" Content="Click me!"/>
</Canvas>
 
 
public static readonly DependencyProperty TopProperty =
    DependencyProperty.RegisterAttached("Top", 
    typeof(double), typeof(Canvas),
    new FrameworkPropertyMetadata(0d,
        FrameworkPropertyMetadataOptions.Inherits));
 
public static void SetTop(UIElement element, double value)
{
    element.SetValue(TopProperty, value);
}
 
public static double GetTop(UIElement element)
{
    return (double)element.GetValue(TopProperty);
}
 
 

Listen to dependency property changes

If you want to listen to changes of a dependency property, you can subclass the type that defines the property and override the property metadata and pass an PropertyChangedCallback. But an much easier way is to get the DependencyPropertyDescriptor and hookup a callback by calling AddValueChanged()

 
DependencyPropertyDescriptor textDescr = DependencyPropertyDescriptor.
    FromProperty(TextBox.TextProperty, typeof(TextBox));
 
if (textDescr!= null)
{
    textDescr.AddValueChanged(myTextBox, delegate
    {
        // Add your propery changed logic here...
    });
} 
 
 

How to clear a local value

Because null is also a valid local value, there is the constant DependencyProperty.UnsetValue that describes an unset value.

button1.ClearValue( Button.ContentProperty );
 




Last modified: 2010-02-08 17:52:30
Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments
Ali
Commented on 27.May 2011
Very Goooddddd !!
Thanks.
Fadi Raheel
Commented on 4.June 2011
Very good explanation of DependencyProperty
Adriano
Commented on 9.June 2011
Could you please put a XAML sample of the binding to the property developed in the code? Thanks.
Jay
Commented on 12.June 2011
The only article that does not confuse readers on Dependency Properties
Hal
Commented on 17.June 2011
Nice attempt at an explanation of DependencyProperty. It could be better organized.
Rene
Commented on 20.June 2011
YES !
Satyabrata
Commented on 24.June 2011
Good, very nice article. Thanks
Stefan
Commented on 5.July 2011
Thank you for spending the time to prepare this article. I have already read the MSDN articles on dependency properties as well as Pro WPF and Silverlight MVVM: Effective Application Development with Model-View-ViewModel (Apress 2010), so understanding your article was easy for me. What is omitted from all of these is a lowest common denominator fully working example that is useful (or at least can be extended to be useful). MSDN uses a silly fish tank example. Provide a second example that builds on the first in order to illustrate the advanced concepts like callbacks.
Aymen
Commented on 17.July 2011
Thanks thanks for this wonderful tutorial it really helped me a lot to understand DependencyProperties , I just still have a question , I don't understand the fact that the dependency property is declared as static so how comes that every instance has its own value this is the only misundestanding I still have I need your help , thanks in advance .
mahanth
Commented on 18.July 2011
Thank you very much.i was looking like this type of article
Tronel
Commented on 21.July 2011
Very useful for me. Thanks
balaji
Commented on 28.July 2011
very nice and useful
daanyaal
Commented on 2.August 2011
You will need to read this about 10 times to Understand what is going on. I understand a little bit now about DP, much better than msnd
Xus
Commented on 3.August 2011
Awesome! Very well explained.
Maya
Commented on 4.August 2011
Very nice explanation on dependency properties............finally understood the concept ! Thanks for posting this.
Ankush Gupta
Commented on 8.August 2011
Good.. Nice Article
Cryptic
Commented on 15.August 2011
I m the beginner of WPF. wow! thts really great to have site like this. Thanks. its helping me a lot.
blah!!!blah!!!
Commented on 19.August 2011
why is the dependency property declared as readonly if you are also using the SetValue method
Rithuu Mangala
Commented on 25.August 2011
Content is Precise and well defined. Thanks for writing this article.
Nahum
Commented on 28.August 2011
Thanks! much clearer than many articles.
seyed
Commented on 6.September 2011
Thank you a lot :)
There is an miistake on Readonly DependencyProperties section. Wrapper method is defined as 'int' but DependencyProperty is already as 'bool'.
Also, i couldn't use 'Listen to dependency property changes' section.
Can you explain some more info about it? Where i must insert these codes?

Thank's again :)
Mayank Gupta
Commented on 16.September 2011
Very Nice Post man
Ohad
Commented on 22.September 2011
Hi Christian
Thanks for your detailed explanation!
I have few questions :
1. At the begining when you expalnied about the advantages one of them was &quot;Reduced memory footprint&quot; u wrote that when using DP it reduces memory storage compare to Normal Properties because it &quot;only stores modified properties in the instance &amp; The default values are stored once within the dependency property&quot;.

I understand that when storring only changes it reduces memory storage but what does it mean that the default values are &quot;stored within the dependency property&quot;? i mean they must be stored somewhere when application runs, so where would that be?
so why DP takes less memory than Normal Property?

2.You wrote that DP are stored in Dictionary instaed of Field like Normal properties.
i wanted to know how is this fact empowers DP compared to normal Prop'. why is it
better?

3.I understood that there are &quot;Readonly DP&quot; but i have noticed that when using the shortcutin Visual Studio for creating regular DP (propdp) a
&quot; public static readonly DependencyProperty MyProperty&quot; is added.
so what is the difference when adding &quot;readonly&quot; statement in regular DP and ReadOnly DP?

4. Maybe a silly question but what is the meaning of &quot;Dependency&quot; in Dependency
Properties?

5. Why is the dependency property must be defined as static?
ohad
Commented on 25.September 2011
Hi Christian
Thanks for your detailed explanation!
I have few questions :
1. At the begining when you expalnied about the advantages one of them was &quot;Reduced memory footprint&quot; u wrote that when using DP it reduces memory storage compare to Normal Properties because it &quot;only stores modified properties in the instance &amp; The default values are stored once within the dependency property&quot;.

I understand that when storring only changes it reduces memory storage but what does it mean that the default values are &quot;stored within the dependency property&quot;? i mean they must be stored somewhere when application runs, so where would that be?
so why DP takes less memory than Normal Property?

2.You wrote that DP are stored in Dictionary instaed of Field like Normal properties.
i wanted to know how is this fact empowers DP compared to normal Prop'. why is it
better?

3.I understood that there are &quot;Readonly DP&quot; but i have noticed that when using the shortcutin Visual Studio for creating regular DP (propdp) a
&quot; public static readonly DependencyProperty MyProperty&quot; is added.
so what is the difference when adding &quot;readonly&quot; statement in regular DP and ReadOnly DP?

4. Maybe a silly question but what is the meaning of &quot;Dependency&quot; in Dependency
Properties?

5. Why DP are always declared as Static?

6. why when updating data from Model to View we have to use DP or NotiftyPropertyChange instead of normal property,

and when updating data from View to Model we have to use Normal Property?

dsd
Commented on 25.September 2011
hello

Name
E-Mail (optional)
Comment