Sunday 8 November 2009

Dependency Properties

Dependency properties are one of the features that allow for extension in WPF.

“Windows Presentation Foundation (WPF) provides a set of services that can be used to extend the functionality of a common language runtime (CLR) property. Collectively, these services are typically referred to as the WPF property system. A property that is backed by the WPF property system is known as a dependency property.”

See http://msdn.microsoft.com/en-us/library/ms752914.aspx

The value of a normal .NET property is read or written directly from or to a field in a class. The value of a DependencyProperty is read or written by calling GetValue() or SetValue() inherited from the DependencyObject base class.

Values are not stored in a field but in a dictionary provided by DependencyObject. The key is the name of the property and the value is the value you want to set.

The advantages of dependency properties include:

  • Change notification
    • Dependency properties have a built-in change notification mechanism so by registering a callback in the property metadata you get notified when the value of the property has been changed. Actions can be triggered in response to this notification like:
      • re-rendering appropriate elements,
      • updating the layout,
      • refreshing data-binding etc.
      • Look-up property triggers.
  • Property value inheritance
    • The value of a dependency property is resolved by using a value resolution strategy (i.e. flowing values down the element tree). But:
      • Not every dependency property participates in property value inheritance.
      • There may be other high-priority sources setting the property value.
  • Support for multiple providers
    • Property value providers can independently attempt to set the value of a dependency property. To avoid chaos there i a defined value resolution strategy.
  • Reduced memory footprint
    • The default values are stored once within the dependency property.

See http://wpftutorial.net/DependencyProperties.html

Sunday 8 November 2009