Wednesday, March 30, 2011

Silverlight 4 Custom Property Binding

A common scenario you might encounter is wanting to create a bindable property on a custom control. The way we do this is using a static DependencyProperty member as our backing field. Below is an example of a CustomTextBox with a string CustomString property:

using System.Windows; 
public class CustomTextBox : System.Windows.Controls.TextBox 
{
    public static readonly DependencyProperty CustomStringProperty = DependencyProperty.Register
        (
            "CustomString",
            typeof(bool),
            typeof(CustomTextBox),
            null 
        );
 
    public string CustomString
    {
        get { return (string)GetValue(CustomStringProperty); }
        set { SetValue(CustomStringProperty, value); }
    } 
}
 
You can now use the CustomTextBox in your XAML, and bind directly to the CustomString property.

Just a simple example to illustrate how its done. If you want more information on how it all works, check out the MSDN documentation.

No comments:

Post a Comment