Setting the value of a dependency property
One of the things I’ve mentioned in the previous posts is that the value of a dependency property at runtime can be influenced by several “providers”. That means that there needs to be some sort of order which governs the way providers affect the final value of a dependency property (this order is known as precedence list). The final value of a dependency property at runtime is obtained after all the items in the following list have been evaluated by the presented order:
- Default value;
- Style setters;
- Templated properties;
- Local value;
- Animations.
The default value of a dependency property depends on whether you’ve passed a default value through the property metadata or not. When you pass a value through the PropertyMetada object during the dependency property registration (my preferred method for defining a default value), that value is used as the default one. If you don’t set the default value through metadata, then the default value depends on the type used for storing the dependency property (reference types use null, value types use the default constructor and primitive types default to the default primitive values – another extra note: the docs say that the default value for a string-type dependency property is the empty string; however, my tests always return null as the default value when string is used as the type of the dependency property. are my tests wrong? or are the docs wrong?).
Style setters will overwrite any style value that has been defined through the default value of a dependency property (you’ll need to look at the docs to see which style values you can define for each control).
Template properties will only be used for objects that are built dynamically from templates. Typically, you’ll end up using TemplateBinding reference for setting the values of the dependency properties. However, you can also define the value of a property directly (without using a TemplateBinding), making that the value of that dependency value in all objects generated from the template.
Local values are set through direct property access or by using the SetValue method inherited from the DependencyObject class. Finally, animation values will always “override” the value of a dependency property. If that was not the case, then the value of the property wouldn’t change and there simply wouldn’t be any animation.
And I guess this sums it up quite nicely…Stay tuned for more on Silverlight.