Thursday, July 7, 2011

Difference between Dependency Property and Normal CLR Property

Dependency Property vs. Normal CLR Property


The Normal CLR property and the dependency property look quite similar but the dependency property is more powerful and has more features. In WPF, dependency properties are used in Animation, Styles, Triggers, Templates, Validation, Data Binding, Layout etc.

CLR property Syntax

private int count;
public int Count
{
   get
   {
      return count;
   }
   set
   {
      count = value;
   }
}

Dependency property syntax

//Registering Dependency Property
public static DependencyProperty PageSizeProperty =
DependencyProperty.RegisterAttached("PageSize",
typeof(int), typeof(AttachedPropertySample),
             new PropertyMetadata(25,
             new PropertyChangedCallback(OnPageSizePropertyChanged)));

//PageSize property declaration
public int PageSize
{
    get
    {
        return (int) GetValue(PageSizeProperty);
    }
    set
    {
        SetValue(PageSizeProperty, value);
    }
}

Major features of Dependency Properties are

Value Resolution
CLR property reads value directly from private member while dependency property dynamically resolves value when you call GetValue() method of dependency property. The GetValue and SetValue methods are inherited from Dependency Object. You can read more about Dependency Property here.

In Built Change Notification
Dependency provides change notification when its value has been changed. You can specify Call Back while registering dependency property so user will get notification. This is mainly used in Data Binding.

Value Inheritance
If you specify dependency property to top element it will inherited to all child elements until child element specifically override the property. Dependency property value is resolved at runtime when you call GetValue() method. 


You might also like
Dependency Property
Attached Property
WPF Architecture

No comments:

Post a Comment