Get the absolute position of an element inside a window in wpf

I would like to get the absolute position of the element relative to the window / root element with a double click. The relative position element inside the parent element is all I can understand, and what I'm trying to find is the point relative to the window. I have seen decisions on how to get the point of an element on the screen, but not in the window.

+63
wpf wpf-positioning
Dec 22 '08 at 16:57
source share
4 answers

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

There is a TransformToAncestor method for this:

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 regarding the position.

+100
Dec 22 '08 at 22:57
source share

To get the absolute position of an interface element in a window, you can use:

 Point position = desiredElement.PointToScreen(new Point(0d, 0d)); 

If you are in a user control and just want the relative position of the interface inside this control, just use:

 Point position = desiredElement.PointToScreen(new Point(0d, 0d)), controlPosition = this.PointToScreen(new Point(0d, 0d)); position.X -= controlPosition.X; position.Y -= controlPosition.Y; 
+33
Mar 21 '13 at 0:31
source share

Add this method to the static class:

  public static Rect GetAbsolutePlacement(this FrameworkElement element, bool relativeToScreen = false) { var absolutePos = element.PointToScreen(new System.Windows.Point(0, 0)); if (relativeToScreen) { return new Rect(absolutePos.X, absolutePos.Y, element.ActualWidth, element.ActualHeight); } var posMW = Application.Current.MainWindow.PointToScreen(new System.Windows.Point(0, 0)); absolutePos = new System.Windows.Point(absolutePos.X - posMW.X, absolutePos.Y - posMW.Y); return new Rect(absolutePos.X, absolutePos.Y, element.ActualWidth, element.ActualHeight); } 

Set relativeToScreen paramater to true to place in the upper left corner of the entire screen or false to place in the upper left corner of the application window.

+13
Jan 28 '14 at 16:59
source share

Hm. You must specify the window that you clicked in Mouse.GetPosition(IInputElement relativeTo) The 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 access the window not from its own class, but from a different point in the application. In this case, Application.Current.MainWindow will help you.

-one
Dec 22 '08 at 18:59
source share



All Articles