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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: