wpf 如何获取子元素相对于父元素的位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1923697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:20:52  来源:igfitidea点击:

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

wpf

提问by tom greene

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

如果a有Canvas父级,很容易得到子级的位置:

Canvas.GetLeft/Top (child)

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

但是我怎样才能为其他类型的父母获得孩子的位置?

回答by Elisha

It can be done using TranslatePointmethod of the control.

它可以使用TranslatePoint控件的方法来完成。

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 TranslatePointwill return the location of that point relative to the parent control (I assumed here the parent is a UIElement).
You can place instead of containerany ancestor of the control.

new Point(0, 0)表示控件的左上角,TranslatePoint并将返回该点相对于父控件的位置(我在这里假设父控件是 a UIElement)。
您可以放置控件的任何祖先而不是容器