如何获取元素在StackPanel中的位置? [英] How to get the position of an element in a StackPanel?

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

问题描述

说我有一个StackPanel,它可以动态地填充副本,从而更改其中的元素的Y位置.在该StackPanel中有一个特定的元素,我想在完成对所有StackPanel的所有子元素的重新放置之后,找到相对于StackPanel的Y位置(相对于StackPanel而言).

Say I have a StackPanel that gets dynamically filled with copy, changing the Y position of elements inside it. I have a specific element within that StackPanel that I want to find the Y position of (relative to the StackPanel or otherwise) after the StackPanel is done repositioning all of it's children.

StackPanel sp = new StackPanel();
sp.Children.Add(someTextBlock);
sp.Children.Add(element1);
sp.Children.Add(element2);
...
someTextBlock.Text = "Lorem ipsum dolor..." // some text that pushes children of > index down
// element1 got pushed down to some unknown position based on text length
// now want to find the Y position of element1

我注意到这样的方法: http://forums.silverlight.net/forums/p/16787/55881.aspx#55881 不起作用,因为返回的位置是StackPanel的位置,而不是我定位的子元素.

I noticed that methods like this: http://forums.silverlight.net/forums/p/16787/55881.aspx#55881 don't work since the position returned is the position of the StackPanel and not the child element I'm targeting.

推荐答案

您发布的链接应该可以正常工作,只要您正确调用它们即可.

The methods in the link you posted should work fine, provided you call them correctly.

您需要使用正确的UIElement进行调用-在这种情况下,对RootVisual使用element1将为您提供 element1 的完整位置:

You need to call them with the correct UIElement - in this case, using element1 to the RootVisual will give you the full position of element1:

var transform = element1.TransformToVisual(Application.Current.RootVisual as FrameworkElement);        
Point absolutePosition = transform.Transform(new Point(0, 0));

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

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