Framework Design Guidelines: Dependency Properties

Continuing in our weekly blog post series that highlights a few of the new image[5]_thumb[2]_thumb[2]_thumbadditions to the Framework Design Guidelines 2nd edition.. This content is found in the Dependency Properties section of Chapter 9: Common Design Patterns. Phil offers some great additions to the base pattern.

The following guidelines describe details of Dependency Property dependency property design.

DO inherit from DependencyObject, or one of its subtypes, when implementing Dependency Properties. The type provides a very efficient implementation of a property store and automatically supports WPF data binding.

DO provide a regular CLR property and public static read-only field storing an instance of System.Windows.DependencyProperty for each Dependency Propertydependency property.

public class TextButton : DependencyObject {
   public string Text {
      get { return (string)this.GetValue(TextProperty); }
      set { this.SetValue(TextProperty,value); }
   }

   public static readonly DependencyProperty TextProperty =
      DependencyProperty.Register("Text",typeof(string),
typeof(TextButton));
   }
}

DO implement Dependency Propertiesdependency properties by calling instance methods DependencyObject.GetValue and DependencyObject.SetValue.

public class TextButton : DependencyObject {
   public string Text {
      get { return (string)this.GetValue(TextProperty); }
      set { this.SetValue(TextProperty,value); }
   }
   public static readonly DependencyProperty TextProperty = …
}

DO name the Dependency Propertydependency property static field by suffixing the name of the property with “Property.”.

The first parameter to the DependencyProperty.Register method should be the name of the wrapper property.

public class TextButton : DependencyObject {
   public static readonly DependencyProperty TextProperty =
       DependencyProperty.Register("Text",typeof(string),
typeof(TextButton));
}