Attached Property Changed Event? [duplicate]

我只是一个虾纸丫 提交于 2019-11-27 16:41:33

问题


ist there a way to get a change notification if an attached property changed?

A simple example is a Canvas with a Rectangle in it. The position of the Rectange is set by using the DepenendyProperties Canvas.Top and Canvas.Left. I'm using an Adorner to move the Rectangle around by changing the Canvas.Top and Canvas.Left.

<Canvas Width="500" Height="500" >
   <Rectangle Width="40" Height="40" Canvas.Left="10" Canvas.Top="20" />
</Canvas>

The next step is to create an Arrow between two Rectangles. In order to keep track of the moving Rectangles the Arrow must get a change notification whenever the position of a Rectanglechanges. This would be easy if I could just get a changed notification when the Attached Property Canvas.Topchanges.

Thanks for any help, Michael


回答1:


Why don't you use a binding ? That's precisely what they're designed for...

If, for some reason, you can't use a binding, you can add a handler to be notified when the value of the property changes :

var topDescriptor = DependencyPropertyDescriptor.FromProperty(Canvas.TopProperty, typeof(Rectangle));
var leftDescriptor = DependencyPropertyDescriptor.FromProperty(Canvas.LeftProperty, typeof(Rectangle));
topDescriptor.AddValueChanged(rectangle, rectangle_PositionChanged);
leftDescriptor.AddValueChanged(rectangle, rectangle_PositionChanged);

...

private void rectangle_PositionChanged(object sender, EventArgs e)
{
    ...
}


来源:https://stackoverflow.com/questions/2462387/attached-property-changed-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!