Monday, November 29, 2010

Dependency Property

For further customization of new UserControl, you can add custom properties to the UserControl's code behind. You can actually add property to it, but for some special functionality like (databinding, animation) with properties, you should add DependencyProperty.
E.g : Here I am explainging how to create a DependencyProperty and use it. Follow the small application, add two textboxes in your user control, I want to change first textbox's text while changing text on second text box. You can do this in 2 ways.
First method using wizard:
1. Click on first text box.
2. Press F4 or go to Properties windows of that textbox.
3. Click on right side of Text column, not in the blank section of Text property.
4. One Context menu will be displayed, choose "Apply Data Binding".
5. Data Binder window will appear, you have to set Source, Path, Converter and Option from there.
6. Here your source will be textbox2 which is an Element.
7. Path will be Value, because you are setting value of TextBox1 to TextBox2 and vice versa.
8. If you want to convert the value in some other format, you can use this.
9. Binding will be TwoWay, if you want to make it for both control.

Second method using Code:
1. You need to create a DependencyProperty. Below is code for that :

public String MyProperty
{
get { return (String)GetValue(MyPropertyProperty); }
set { SetValue(MyPropertyProperty, value); }
}
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty", typeof(String), typeof("ownerType"), new PropertyMetadata("MyProperty"));
2. Go to design view, select TextBox1. Add "{Binding MyProperty, Mode=TwoWay}" piece of code in both textbox's Text property.

No comments: