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;
    ...
}
Published Monday, July 13, 2009 3:41 PM by marianor
Filed under:

Comments

# How to get notifications in attached properties - Unknown Recipes

Pingback from  How to get notifications in attached properties - Unknown Recipes

# How to get notifications in attached properties | I love .NET!

Pingback from  How to get notifications in attached properties | I love .NET!

# How to get notifications in attached properties | Nexo IT - Information Technology News

Pingback from  How to get notifications in attached properties | Nexo IT - Information Technology News

Leave a Comment

(required) 
(required) 
(optional)
(required)