查找图形对象相对于其他 Canvas 的确切位置 [英] Finding the exact position of a graphical object in relation to some other Canvas

查看:21
本文介绍了查找图形对象相对于其他 Canvas 的确切位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ListBox,当我在该 ListBox 中选择一个项目时,我想复制该图像并将其放置在包含我的应用程序中所有其他对象的 Canvas 上.这在大多数情况下工作正常,但是如果 ListBox 中的项目位于更远的位置,以至于我必须滚动才能看到该项目,则坐标不再准确.

I have a ListBox, and when I select an item in that ListBox I want to duplicate the image and place it on the Canvas containing all the other objects in my app. This works fine for the most part, however if the item in the ListBox is further in, such that I have to scroll to see the item, the coordinates are no longer accurate.

是否有像 Canvas.getGlobalPosition(UIElement) 这样的函数,它可以让我设置 Canvas.SetTop(uiElement, globalCoordinateSpace.Y) 并让我可以完美地将一个图像直接放在另一个之上,无论在哪里在它所在的 ListBox 中?

Is there a function such as Canvas.getGlobalPosition(UIElement), which would allow me to then set Canvas.SetTop(uiElement, globalCoordinateSpace.Y) and allow me to perfectly place one image directly ontop of the other, no matter where in the ListBox it resides?

谢谢.

推荐答案

您可以使用方法 TransformToVisual 以创建允许您确定一个元素相对于另一个元素的位置的变换.

You can use the method TransformToVisual to create transform that allows you to determine the location of one element with respect to another.

我经常使用下面的扩展方法来让我确定两个UIElements的相对位置:

I often use the following extension method to allow me to determine the relative position of two UIElements:

    /// <summary>
    /// Gets the relative position of the given UIElement to this.
    /// </summary>
    public static Point GetRelativePosition(this UIElement element, UIElement other)
    {
        return element.TransformToVisual(other)
                      .Transform(new Point(0, 0));
    }

您可以通过在 Application.Current.RootFrame 上调用上述代码来获取屏幕上的确切位置.

You can get the exact on-screen position by invoking the above code on Application.Current.RootFrame.

这篇关于查找图形对象相对于其他 Canvas 的确切位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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