如何获取子元素相对于父元素的位置? [英] How can I get the position of a child element relative to a parent?

查看:56
本文介绍了如何获取子元素相对于父元素的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

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) 表示控件的左上角,TranslatePoint 将返回该点相对于父控件的位置(我假设在这里父元素是 UIElement).
您可以放置​​控件的任何祖先而不是容器.

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.

这篇关于如何获取子元素相对于父元素的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆