Thursday, May 09, 2013

Difference Between Dependency Property and Normal CLR Property in WPF

Difference Between Dependency Property and Normal CLR Property in WPF

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.

Syntax Difference Between Dependency Property and Normal CLR Property

Syntax of Normal CLR Property

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

Syntax of Dependency Property

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

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

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. But CLR property has not any inbuilt change notification. So if you want your normal CLR proprety also notify changes, you have to implement INotifyPropertyChanged.

QR: Inline image 1