This Qikkwit will explain WPF Dependency properties and its advanced features. Dependency properties use more-efficient storage and support additional features such as change notification and property value inheritance (the ability to propagate default values down the element tree). Dependency properties are also the basis for a number of key WPF features, including animation, data binding, and styles.
If you are defining custom controls then you have to define DependencyProperties to take advantage of DataBinding of WPF. As these properties should be available all the time and even can be shared through classes they must be declared public static. To differentiate dependency property from other word Property is suffixed at end of name.
Dependency properties can be only belonged to DependencyObject or classes derived from it. Most of the WPF elements are derived from DependencyObject hence all of them support DependencyProperty framework. To use it we must first register it with WPF system. Registration should be done before anyone can use it hence it is done in static constructor.
Once created it cannot be changed as all its members are static and readonly. Hence they need to be set while registering only. You have supply following five values while registering
- Name of dependency property
- Type of dependency property
- Owner type
- FrameworkPropertyMetadata (optional)
- AffectMeasure : E.g. if it changes then container has replace elements
- AffectRender: E.g. if property changes then control needs repaint
- Validation call back (optional)
You can create wrapper around the dependency property to set and get the value of it through SetValue and GetValue functions. DependencyProperty calls a function OnPropertyChangeCallback once its value changes which is basis for data binding and triggers.
Dynamic value resolution is another major feature of DependencyProperty. When you try to get value of dependency property WPF takes cares lot of factors and their precedence to arrive at right base value of the property. Following are the factors from lowest to highest importance
- Default value
- Inherited value
- Value from theme style
- Value from project style
- Local value
Once the base value is fixed now WPF go through following process to arrive at final value
- Determine base value
- If property is set to some expression like binding or resource then evaluate that expression.
- If property is target of animation then apply that animation
- Run coerce value callback
Dependency Properties can be shared by calling AddOwner method. They can also be attached by calling RegisterAttached, where they are defined in class which does not own it.
DependencyProperty validation can be done by ValidationValueCallBack and then by CoerceValueCallback. Both are static methods hence can be reused.