Archive | March, 2010

Dependency Property Basics

5 Mar

When working with WPF it can be necessary to extend a control to enable data-binding to a property that isn’t bind-able (because it is not a dependency property etc.). The following code demonstrates an example I have made where I override a Text property and give it a dependency property to enable data-binding.

 

public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(TextEditorControl), new FrameworkPropertyMetadata(OnTextPropertyChanged));

 

private static void OnTextPropertyChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)

{

    //TODO: action handler here

}

 

public override string Text

{

    get

    {

        return (string)GetValue(TextProperty) ?? string.Empty;

    }

    set

    {

        base.Text = value;

 

        SetValue(TextProperty, value);

    }

}

 

The code also shows how to handle the event raised when the binding source (the view model) is updated. I recommend using dependency properties for WPF controls; as for view model classes I recommend implementing the INotifyPropertyChanged interface instead.