WPF:获取子 UIElement 在其父级中的位置。忽略 RenderTransform(如果有)
假设我有以下 XAML 代码:
<DockPanel Name="pan">
<Label Content="AAA" Name="lab1" />
<Label Content="BBB" Name="lab2" />
<Label Content="CCC" Name="lab3" />
</DockPanel>
我的代码背后是我想找出 pan
中 lab2
的坐标。 然而我想忽略lab2
任何存在的RenderTransform。因此,解决方案必须为上述代码和以下代码返回相同的坐标:
<DockPanel>
<Label Content="AAA" />
<Label Content="BBB" >
<Label.RenderTransform>
<TranslateTransform Y="20"/>
</Label.RenderTransform>
</Label>
<Label Content="CCC" />
</DockPanel>
换句话说,我想要在调用 Arrange< 时由
pan
的 ArrangeOverride
方法设置的位置but2
上的 /code>。我将其称为“逻辑位置”。可以通过调用以下方法来获取“视觉位置”:
private Point visualPoss() {
Point lab2Vis = lab2.PointToScreen(new Point(0, 0));
Point panVis = pan.PointToScreen(new Point(0, 0));
return new Point(lab2Vis.X - panVis.X, lab2Vis.Y - panVis.Y);
}
但这并不是我的问题的解决方案,因为对于上面的两个 XAML 代码示例,此 visualPoss()
的返回值并不相等。
如果有不清楚的地方请发表评论。
谢谢
Lets say I have this XAML code:
<DockPanel Name="pan">
<Label Content="AAA" Name="lab1" />
<Label Content="BBB" Name="lab2" />
<Label Content="CCC" Name="lab3" />
</DockPanel>
I my code behind I want to find out what are the coordinates of lab2
within pan
. Hovewer I want to ignore any present RenderTransform of lab2
. So the solution must return same coordinates for above code and following:
<DockPanel>
<Label Content="AAA" />
<Label Content="BBB" >
<Label.RenderTransform>
<TranslateTransform Y="20"/>
</Label.RenderTransform>
</Label>
<Label Content="CCC" />
</DockPanel>
In another words I want the position that was set by the ArrangeOverride
method of pan
when calling Arrange
on but2
. I would call it 'logical position'. The 'visual position' can be obtained by calling following method:
private Point visualPoss() {
Point lab2Vis = lab2.PointToScreen(new Point(0, 0));
Point panVis = pan.PointToScreen(new Point(0, 0));
return new Point(lab2Vis.X - panVis.X, lab2Vis.Y - panVis.Y);
}
But this is not a solution of my problem as the return value of this visualPoss()
is not equal for both XAML code examples above.
Please leave comment if somehing is unclear.
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来有一个非常简单明了的解决方案:
看起来运行良好。如果您知道它何时不起作用的场景,请发表评论。
It looks like there is very simple and clear solution:
It looks like it is working well. If you know abou the scenerio when it will not work please leave a comment.
我将获得变换,并将其转换为 MatrixTransform。然后,您可以使用 Inverse 属性来反转渲染变换。它看起来像这样:
I would get the transform, and convert it to a
MatrixTransform
. You can then use the Inverse property to reverse the render transform. It would look something like so: