How to get notifications in attached properties

Sometime we need to know when an attached property change its value for a specific FrameworkElement. For example consider the following:

<Canvas>
  <Button x:Name="move" Content="Move" Canvas.Left="10" Canvas.Top="10"/>
</Canvas>

If in a part of the code we have something like:

Canvas.SetLeft(this.move, 20);

And we need listen when the Left attached property changed for the button, we can use a DependencyPropertyDescriptor to do it. This class provides the FromProperty static method, which gives as an instance of itself receiving the DependencyProperty:

var descriptor = DependencyPropertyDescriptor.FromProperty(
    Canvas.LeftProperty,
    typeof(Button));

Once we have the instance of the DependencyPropertyDescriptor we can use it to get the notifications using AddValueChanged method:

descriptor.AddValueChanged(this.move, this.OnValueChanged);

Finally we need to implement the event handler:

private void OnValueChanged(object sender, EventArgs e)
{
    var button = (Button)sender;
    ...
}

3 Comments

  • Thanks! This was driving me nuts for some time... I was passing in the wrong targetType to FromProperty and component to AddValueChanged for an inherited attached property.

  • This seems to have a misleading title: your blog describes how to listen to dependency properties (and this is what you show), not attached properties.

  • As you can see the property I am using is Canvas.LeftProperty which is clearly an attached property.
    This same method work for dependency and attached properties.

Comments have been disabled for this content.