Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • WPF : Dependency Property

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 753
    Comment on it


    Introduction :

     

    A dependency property is a type of property which extends the CLR property by adding more functionality. The difference between the two is, that while the value of a .NET property is fetched directly from a private member in the  class, the value of a DependencyProperty is resolved dynamically by calling the GetValue() method which is inherited from DependencyObject.


    Major advantages of dependency property :

     

    1) Property Value Inheritance:
        This ensures that the value with highest precedence is set. We will cover more details later in the article.

     

    2) DataBinding:
        Data binding is supported  since all the dependency properties invoke INotifyPropertyChanged on change in property value.

     

    3) Data Validation:
       We can ensure that on change of property value  data validations are triggered automatically .


    4) Callbacks:
        Dependency properties support callback ensuring a callback is raised on change of property value.


    5) Animation:
       Dependency property can be used for supporting Animation for that property.


    6) Templates:
       Dependency properties can be used in templates.

     

    7) Styles:
       Styles can be used on dependency properties.


    8) Resources:
       We can define a resource in XAML for the definition of a dependency property.


    Property Value Inheritance :

     

    The  term  refers to the flowing of property values down an element tree. WPF follows a five-step process for each dependency property to get it's final value.


    1) Determine the Base Value
       Following is the list of ten providers that can set the value of most dependency properties which in turn  affects base value calculation.
       a) Local value
       b) Parent template trigger
       c) Parent template
       d) Style triggers
       e) Template triggers
       f) Style setters
       g) Theme style triggers
       h) Theme style setters
       i) Property value inheritance
       j) Default value

     

    2) Evaluate
       If the result of Step 1 is an expression then WPF converts the expression into concrete result.

     

    3) Apply Animations
       Animations can change the property value based on the value received form Step 2 even to extent of completely replacing it.

     

    4) Coerce
       In this step if a CoerceValueCallback  delegate is registered with the dependency property and the current property value is passed to it then it is modified by a custom logic and returned via callback.

     

    5) Validate
       Finally  if a ValidateValueCallback  delegate is registered with the dependency property and the current property value is passed to it then this callback returns true if the input value is valid else false which aborts the entire process.

     
    Dependency Property Creation :

     

    In order to create a dependency property we  need to create an instance and register it as below.

     

    public static readonly 
      DependencyProperty MyDPProperty = 
         DependencyProperty.Register(
                                 "MyDependencyProperty",
                                 typeof(double),
                                 typeof(ClassType));

     

    There are a number of overloads to the register method but the minimum we need to specify are below:

    1) The name of the property as a string "MyDependencyProperty".

    2) The type of the property  typeof(double).

    3) The type of the class the property belongs to typeof ( ClassType ).

     

    Read Only Dependency Property:

     

    Sometimes in an application we might require a read only dependency property. Creating it is slightly different from creating a standard dependency property. Following are the steps for creating read only dependency property:

    a) Use DependencyProperty.RegisterReadOnly instead of Register
     

    b) Create an internal static copy of a DependencyPropertyKey in addition to a public static DependencyProperty

     

           internal static readonly DependencyPropertyKey ReadOnlyPropertyKey =  DependencyProperty.RegisterReadOnly("ReadOnly", typeof(int), typeof(Person), new PropertyMetadata(100));
          
           public static readonly DependencyProperty ReadOnlyProperty = ReadOnlyPropertyKey.DependencyProperty;


       Here PropertyMetadata is property metadata for the dependency property.


    c) Provide a CLR property wrapper

     

       public int ReadOnly
       {
         get { return (int)GetValue(ReadOnlyProperty); }
    
       }
    

     

    Attached Property:

     

    An attached property is a type of global property that can be set on any object. In WPF , attached properties are often seen as a specialized form of dependency property that do not have the conventional property wrapper.


    The following example shows the dependency property registration via the RegisterAttached method.It also shows how to use the GetPropertyName and SetPropertyName accessors. In the example,the attached property name is IsAttachedProperty. Therefore, the accessors must be named GetIsAttachedProperty and SetIsAttachedProperty.

     

           public static readonly DependencyProperty IsAttachedToProperty = DependencyProperty.RegisterAttached(
                                "IsAttachedProperty",
                                 typeof(Boolean),
                                 typeof(AquariumObject),
                                 new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender)
                                                                                                        );
            public static void SetIsAttachedProperty(UIElement element, Boolean value)
            {
                element.SetValue(IsAttachedToProperty, value);
            }
            public static Boolean GetIsAttachedProperty(UIElement element)
            {
                return (Boolean)element.GetValue(IsAttachedToProperty);
            }

     

    Custom Dependency Property :

     

    Let us now see a dependency property in action by creating a custom dependency property as below :

     

        public class ClassProperty : DependencyObject
        {
            public double MyDependencyProp
            {
                get
                {
                    return (double)GetValue(MyDependencyProperty);
                }
                set
                {
                    SetValue(MyDependencyProperty, value);
                }
            }
    
            public static readonly
                 DependencyProperty MyDependencyProperty
                     = DependencyProperty.Register(
                                         "DProp",
                                         typeof(double),
                                         typeof(ClassProperty));
        }

     


    Before we proceed further we need to add a slider control to the form. We will be binding the slider control to the dependency property we have created.

     

         ClassProperty obj = new ClassProperty();
         obj.MyDependencyProp = 6;
         Binding myBinding = new Binding("DProp");
         myBinding.Source = obj;
         slider1.SetBinding(Slider.ValueProperty,myBinding);

     


    In the above code we create an instance of binding object and bind it to an object containing dependency property. When we run the above piece of code we will see the slider control has moved to a value corresponding to 6 (a predefined value).


    Conclusion :

     

    In this article we explored the various aspects of dependency properties from creation to implementation . Dependency properties are powerful constructs and are used extensively in WPF. For more details you may check the following link (http://www.informit.com/articles/article.aspx?p=2115888)

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: