tom greene
tom greene

Reputation: 5449

How can I get the position of a child element relative to a parent?

If a have a Canvas parent, it is very easy to get the position of a child:

Canvas.GetLeft/Top (child)

But how can I get the position of a child for other types of parents?

Upvotes: 51

Views: 46170

Answers (1)

Elisha
Elisha

Reputation: 23770

It can be done using TranslatePoint method of the control.

UIElement container = VisualTreeHelper.GetParent(control) as UIElement;
Point relativeLocation = control.TranslatePoint(new Point(0, 0), container);

new Point(0, 0) represents the top left point of the control and TranslatePoint will return the location of that point relative to the parent control (I assumed here the parent is a UIElement).
You can place instead of container any ancestor of the control.

Upvotes: 97

Related Questions