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));
}

Comments (13)

  1. What's New says:

    Continuing in our weekly blog post series that highlights a few of the new additions to the Framework

  2. Thank you for submitting this cool story – Trackback from DotNetShoutout

  3. Ashic says:

    Erm…why can’t dependency objects be datacontexts in silverlight (and work properly) when INotifyPropertyChanged implementations can? I like the dependency approach but would like it more if silverlight supported dependency object data contexts.

  4. sambo99 says:

    If you use PostSharp you will not need any of the setter/getter mess

  5. Alex O. says:

    This new "guideline" addition left me wondering if the FDG 2 has gotten polluted with too many implementation nuances of transient technologies.

    I gladly purchased and read the first FDG book, because it provided such a concise and clear guidance on the fundamental aspects of the general design and left out numerous technology-specific details. This was a welcome break from the avalanche of "click on menu item xyz" books that tell you nothing about the underlying concepts and instead load your brain with a slew of mouse click instructions that will be largely irrelevant in the version 2.x of the same product/technology.

    I feel that these latest "guidelines" belong in the MSDN library describing details of the WPF technology, not in the timeless FDG book. If I pick up your book 5 or 10 years from now, the nitty-gritty WPF-specific suggestions will most likely have no real value to me, but the class vs. interface discussion or the exception handling topics hopefully would still make a lot of sense.

    Don’t get me wrong: I still love the book and permanently keep FDG 2 on my Safari bookshelf. I believe that EVERY developer should use this book as a daily reference.

  6. Mark Gordon says:

    I found it interesting you used UI controls in your example. Given the class browser doesn’t support subclassing UI controls and there are also various issue in coding them out like you have that need to be worked around. Furthermore WPF which I assume is the direction microsoft is taking, at least today, composition UI controls aren’t subclassed which IMHO is a huge issue.

  7. Krzysztof Cwalina says:

    Alex thanks for the feedback, both the praise and the skepticism around some additions. We had many similar discussions when we tried to decide what to add to the 2nd edition. Such decisions are tricky as there is no clear line between the timeless and the not so timeless. If CLR added support for multiple inheritance, even the interface vs. abstract class discussion would become irrelevant. I have to admit that the guidelines related to dependency properties are on the lower end of “timelessness”.

    Secondly, (and here I would be interested in opinions people have) I wonder if timelessness is the only/main criteria we should use when we decide what to add into the [hypothetical :-)] future edditions. We have many guidelines that we developed internally, that are not even close to be timeless, but I think they can be very useful to the community.

  8. sambo99 says:

    @kcwalina

    The big problem I have with this guideline is that it is encouraging ugly, overly verbose code which is very domain specific. When C# has aspects this will be a lot cleaner. Anyway the reason, I think, this mess is needed is because of a design flaw in WPF.

    So, for example, this is less ugly. But not really implementable at the moment.  

    [DependencyProperty]

    public string Text {

         get;  

         set;

    }

    I think FDG book should focus on timeless elegant code, and less on domain specific hacks.

    But … I also think there is a place for guidelines like this, perhaps you guys need a moderated stackoverflow like web site for design guidelines. The thing is, that guidelines like this get outdated really quickly with later versions of frameworks, somewhere down the line you are stuck with a book in print that has "bad" patterns in it.

  9. Alex O. says:

    @sambo99: well said about the "bad" patterns.

    I have recently decided that from now on I would only purchase in-print books that have this "timeless" quality about them, like FDG, Martin Fowler’s "Refactoring" or Gerard Meszaros’ "xUnit Test Patterns".

    Of course, I still read a bunch of technology-specific point-and-shoot books, but I either buy them in eBook format or read them on the Safari.

    One other characteristic that I really liked about FDG – it is not bloated in size, not a 1500-page "bible". In my opinion, if the book spills over 400-500 pages, it is either too diluted (mainly for the sales appeal) or attempts to cover too many topics at the expense of not delivering a cohesive message. Such books are not practical to read in print and you cannot take it with you on the plane to Bahamas :)

    So, my bottom-line preferences for the future FDG books:

    1.Manageable size (<500 pages)

    2.Light on the technology, heavy on the concepts

    3.No repeated code snippets (opposite to what we have seen in this guideline, where TextButton code appeared twice in the back-to-back DOs)

  10. Aleksander Polak says:

    Thanks for sharing the guidelines. In my opinion, however, one essential guideline is missing:

    DO NOT implement any additional logic in dependency property get and set accessors apart from calling instance methods DependencyObject.GetValue and DependencyObject.SetValue.

  11. johnzabroski says:

    Hilarious.

    I was just about to comment on what Polak said above, but he beat me to it.

    How can you miss the ONE guideline that is mentioned in just about every respectable WPF book?

    Also I agree with the others, this crap pollutes an otherwise neutral book with transient technologies.  Time should be better spent providing staticanalysis tools that veirfy correct implementations.  Likewise, T4 could be used to automate a lot of the cruft that is this awful WPF subsystem design.  I would also add one other important guideline:

    DO NOT use DependencyProperty or DependencyObject on your domain types.

    DO use INotifyPropertyChanged, or inherit your domain type from an object that implements INotifyPropertyChanged (ObservableCollection).

  12. johnzabroski says:

    @cwalina

    @We have many guidelines that we developed internally, that are not even close to be timeless, but I think they can be very useful to the community.

    So publish a .NET 3.0 Foundation Class Libraries Usage Design Guideleins book,