Finding the exact position of a graphical object in relation to some other Canvas

余生颓废 提交于 2020-01-17 04:49:08

问题


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.

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?

Thanks.


回答1:


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

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));
    }

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



来源:https://stackoverflow.com/questions/9179142/finding-the-exact-position-of-a-graphical-object-in-relation-to-some-other-canva

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!