views:

7143

answers:

4

I would like to get the absolute position of an element in relation to the window/root element when it is double clicked. The element's relative position within it's parent is all I can seem to get to, and what I'm trying to get to is the point relative to the window. I've seen solutions of how to get a the point of an element on the screen, but not in the window.

A: 

Hm. You have to specify window you clicked in Mouse.GetPosition(IInputElement relativeTo) Following code works well for me

protected override void OnMouseDown(MouseButtonEventArgs e)
    {
        base.OnMouseDown(e);
        Point p = e.GetPosition(this);
    }

I suspect that you need to refer to the window not from it own class but from other point of the application. In this case Application.Current.MainWindow will help you.

Oleg
+14  A: 

I think what BrandonS wants is not the position of the mouse relative to the root element, but rather the position of some descendant element.

For that, there is the TransformToAncestor method:

Point relativePoint = myVisual.TransformToAncestor(rootVisual)
                              .Transform(new Point(0, 0));

Where myVisual is the element that was just double-clicked, and rootVisual is Application.Current.MainWindow or whatever you want the position relative to.

Robert Macnee
Hi i tried this and i get the following exception: System.InvalidOperationException was unhandled Message=The specified Visual is not an ancestor of this Visual. Source=PresentationCore Any idea?
Roflcoptr
A: 

Thanks for response, that is what I was looking for.

BrandonS
A: 

http://ivolo.mit.edu/post/WPF-Mouse-and-Point-Acrobatics.aspx

describes how to get relative/absolute position of the mouse or any element.

Ilya