What’s the deal with dependency properties?

With in a span of last few weeks; more people have asked me the same question over and over again –

Below is my rant on the same:

  • what’s the deal with dependency properties?

I seriously think that dependency properties is one thing which didn’t get the respect and attention it deserved. I mean when i first discovered it; i was in awe!!  Its such a strong concept that i was mesmerised by both its power and even based few of my “design” on its principle!! for a understanding on DPs consider my previous blog in DP!!

What is the difference between using methods and properties? Well; plain properties ARE at the end the days get_*() and set_*() methods;then why use a property? 

First and foremost; properties encapsulate calls to the methods (and thus make a piece of code a component!!) – that is well understood!! however; there is another way to look at it.

There is a need to invoke and declare component in some kind of serializable (declarable) standard (think aspx, XAML, XML) which “templatize” code without the need to explicitly write code to invoke methods from “code-behind”. The only answer is to make properties which can be use declaratively. For example: Animations can be defined declaratively in XAML itself because of DPs. Imagine if DPs was not around; we will be needing loads of “code behinds” to make things work!! Button, class for example have 78 out of Button‘s 96 properties as dependency properties,… Properties can be easily set in XAML (directly or by Blend) without any procedural code

Even more intriguing is the fact how easily we can implement Inversion of Control (dependency Injection) using the same!! I have wondered that’s why it is called dependency property??for e.g.:

Attached properties like <Button Canvas.Top="10" />.

Instead of Canvas class deciding where the button should be placed, Button class is responsible for  positioning itself with respect to Canvas class… the dependencies have been reversed!! by the way in code behind the above code will be like: Button.SetValue(Canvas.TopProperty, (double)10.0);

by the way; I always had thought that i have a clear understanding of the Attached properties and dependency property and Attached property is a special case of dependency property until i came across this blog by silverlight Geek Jesse Liberty. I was convinced that the above is attached property; but as you can see in the blog; Tim Heuer prefers calling it an dependency property!! and it all depends how we look at it!!

  • why can’t CLR properties behave like DPs?

The difference is that CLR properties are understood by the compiler, they are part of the language, whereas DPs are purely implementation being part of the framework rather than the language. The compiler has no understanding of DPs hence there is no shorthand available. Notice “DependencyProperty.Register” while declaring a DP….

  • DP’s CLR property wrappers should  not contain any logic in addition to the GetValue/SetValue calls.

CLR property wrapper provide convenience at compile-time; At run-time XAML calls the underlying GetValue and SetValue methods directly!! Therefore, to maintain parity between setting a property in XAML and procedural code..

Consider below code:

// ExtendedStackPanel  implementing a DP

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace DP
{
    public class ExtendedStackPanel : StackPanel
    {
        public string MyProperty
        {
            get {
               MyProperty = "This is never executed!!";
                return (string)GetValue(MyPropertyProperty); }
            set {
                value = "changed value by writing code in CLR property encapsulating DP, who needs a callback for DP. But think when someone calls it from procedure code as object.SetValue() directly !!";
                SetValue(MyPropertyProperty, value); }
        }

        // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc…
        public static readonly DependencyProperty MyPropertyProperty =
            DependencyProperty.Register("MyProperty", typeof(string), typeof(ExtendedStackPanel), new PropertyMetadata("default"));
    }
}

calling the above clas in main XAML as

<StackPanel x:Name="LayoutRoot">
       <DP:ExtendedStackPanel x:Name="sp" MyProperty="This is a heading set as DP!!" Background="Aqua">
           <ContentPresenter Content="{Binding ElementName=sp, Path=MyProperty}" ></ContentPresenter>
       </DP:ExtendedStackPanel>
       <DP:ExtendedStackPanel x:Name="sp1"  Background="AliceBlue">
           <ContentPresenter Content="{Binding ElementName=sp1, Path=MyProperty}" ></ContentPresenter>
       </DP:ExtendedStackPanel>
</StackPanel>

and code behind:

this.Loaded += new RoutedEventHandler((o,e)=>
            {
                // this will NOT call the wrapper property around DP!!
                sp1.SetValue(ExtendedStackPanel.MyPropertyProperty, "this is text value set from procedural code!! does NOT calls CLR property !! Code written in CLR property is not even executed!!");
            });
            // does not return "This is never executed!!"; as you will expect!!
            string s = sp.MyProperty;

I have uploaded the full code here for above code; in case you want to play around with it!!

All in all; XAML was a big leap forward on top of .net 2.0 because of “Eventing system” and “property system”. If it hadnt been for a strong concept like DPs; declarative languages like XAML would not have been possible.  I wish i could go on and on about use an efficient sparse storage system in DPs and use of static. But to keep focus on ONLY answering the question i must end here.

Please do provide your feedback…

Technorati Tags: ,