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

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

问题描述

假设我有一个 StackPanel,它会动态填充副本,更改其中元素的 Y 位置.我在 StackPanel 中有一个特定元素,我想在 StackPanel 重新定位所有子项后找到(相对于 StackPanel 或其他方式)的 Y 位置.

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 调用它们 - 在这种情况下,将 element1 用于 RootVisual 将为您提供 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天全站免登陆