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

前端 未结 1 552
夕颜
夕颜 2020-12-05 06:13

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 c

相关标签:
1条回答
  • 2020-12-05 06:49

    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.

    0 讨论(0)
提交回复
热议问题