Finding the exact position of a graphical object i

2019-08-31 09:57发布

问题:

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.