Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

wpf

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?

like image 723
tom greene Avatar asked Dec 17 '09 18:12

tom greene


People also ask

How do you position an element relative to a parent?

Absolute In position: relative , the element is positioned relative to itself. However, an absolutely positioned element is relative to its parent. An element with position: absolute is removed from the normal document flow. It is positioned automatically to the starting point (top-left corner) of its parent element.

Can position fixed be relative to parent?

fixed : the element is removed from the flow of the document like absolutely positioned elements. In fact they behave almost the same, only fixed positioned elements are always relative to the document, not any particular parent, and are unaffected by scrolling.

How do you position relative elements?

An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled. The top, right, bottom, and left properties are used to position the element. A fixed element does not leave a gap in the page where it would normally have been located.

What will be the position of the element if you set position relative on an element with no positioning attributes top bottom left right )?

If you set position: relative; on an element but no other positioning attributes ( top , left , bottom or right ), it will have no effect on it's positioning at all, it will be exactly as it would be if you left it as position: static; But if you do give it some other positioning attribute, say, top: 10px; , it will ...


1 Answers

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.

like image 99
Elisha Avatar answered Oct 13 '22 08:10

Elisha