How can I execute code when a dependency property is set?

When you define a dependency property, you create an associated traditional property wrapper as shown in this example:

/// <summary>
/// BindingSource dependency property
/// </summary>
public static readonly DependencyProperty BindingSourceProperty =
	DependencyProperty.Register("BindingSource", typeof(string), typeof(mmButtonBehavior));

/// <summary>
/// BindingSource dependency property wrapper
/// </summary>
[Category("Data"),
Description("The name of the source business object class to bind this control.")]
public string BindingSource
{
	get { return (string)GetValue(BindingSourceProperty); }
	set { SetValue(BindingSourceProperty, value); }
}

If you want to execute code when the property value is set, you should NOT place it in the set() of the property wrapper, because the dependency property may not always be accessed through this wrapper. The correct approach is to use a property changed callback. Notice the additional PropertyMetadata parameter passed in this dependency property declaration:

/// <summary>
/// BindingSource dependency property
/// </summary>
public static readonly DependencyProperty BindingSourceProperty =
	DependencyProperty.Register("BindingSource", typeof(string), typeof(mmButtonBehavior),
	new PropertyMetadata(null, new PropertyChangedCallback(OnBindingSourceChanged)));

/// <summary>
/// BindingSource dependency property wrapper
/// </summary>
[Category("Data"),
Description("The name of the source business object class to bind this control.")]
public string BindingSource
{
	get { return (string)GetValue(BindingSourceProperty); }
	set { SetValue(BindingSourceProperty, value); }
}

protected static void OnBindingSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
	mmBindingStrategyBase.RegisterBoundElement(d as ImmBinding);
}

The PropertyMetaData object's constructor is passed two parameters. The first is the default value of the dependency property. the second parameter is a PropertyChangedCallback object that contains a reference to the OnBindingSourceChanged method. Whenever the BindingSource property is changed, the OnBindingSourceChanged method is automatically executed.


© (c) 2026 Oak Leaf Enterprises, Inc., 1996-2026 • Updated: 10/23/10
Comment or report problem with topic