Use of dependency property in silverlight.


Introduction : This blog shows How we use dependency property in silverlight.

Explanation :

1.a Dependency Property is like any other property but can hold a default value, with built in mechanism for property value validation and automatic notification for changes in property value .

any binding in silverlight is to binded to a Dependency Property.

Dependency properties can hold an optional default value, and can propagate the default value down the element tree.

2.Registering a Dependency Property

  Dependency Properties have to be registered using DependencyProperty.Register method.
  method of DependencyProperty.Register  takes 4 parameters,

  1.Name of the property to be registered
  2.Data type of the Dependency Property being registered
  3.Owner (Data type of parent) of the Dependency Property being registered (typically the root class). 
  4.Metadata of the Dependency Property (Optional by specifying null (C#)/Nothing (VB.NET))
   public static readonly DependencyProperty ValueProperty=
   ValueProperty = DependencyProperty.Register("Value", typeof(int), typeof(FrameworkElement), null);

3.Reading and Writing Dependency Property values

  Getting Dependency Property Value:

  The method to be used to get the value of a Dependency Property is GetValue().
  GetValue(FrameworkElement.ValueProperty);
  Setting Dependency Property Value:
  The method to be used to set the value of a Dependency Property is SetValue().
  SetValue(FrameworkElement.ValueProperty, 4);
  public int Value
{
    get
    {
        return (int) GetValue(ValueProperty);
    }
    set
    {
        SetValue(ValueProperty, value);
    }
}
4.Example :
 The most common dependency property used is the Grid.Row/Grid.Column properties.
 
 If we have a button and set it's "grid related" properties let's say to grid.row="1"
 and grid.column="1", when we put our button inside a grid it should appear in row1/col1 of that grid,
 but, if we put the same button inside a stackPanel the button should just appear inside the stackPanel.
 Before we add the button to the grid.children collection, we can set this row/col properties like:

 btn.SetValue(Grid.RowProperty, 1)
 btn.SetValue(Grid.ColumnProperty, 1)
 then we just use myGrid.Children.Add(btn) and the button will get to the correct row/column "of the grid"
Ebook Download
View all
Learn
View all