Chciałbym uzyskać bezwzględną pozycję elementu w stosunku do elementu window / root po dwukrotnym kliknięciu. Względne położenie elementu w jego rodzicu to wszystko, do czego mogę się dostać, a to, do czego próbuję dotrzeć, to punkt względem okna. Widziałem rozwiązania, jak uzyskać punkt elementu na ekranie, ale nie w oknie.
wpf
wpf-positioning
BrandonS
źródło
źródło
To get the absolute position of an UI element within the window you can use:
Point position = desiredElement.PointToScreen(new Point(0d, 0d));
If you are within an User Control, and simply want relative position of the UI element within that control, simply use:
Point position = desiredElement.PointToScreen(new Point(0d, 0d)), controlPosition = this.PointToScreen(new Point(0d, 0d)); position.X -= controlPosition.X; position.Y -= controlPosition.Y;
źródło
Add this method to a 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 totrue
for placement from top left corner of whole screen or tofalse
for placement from top left corner of application window.źródło
RenderTransform
of the element, and therefore it needs to know the absolute position of the element on the screen.Since .NET 3.0, you can simply use
*yourElement*.TranslatePoint(new Point(0, 0), *theContainerOfYourChoice*)
.This will give you the point 0, 0 of your button, but towards the container. (You can also give an other point that 0, 0)
Check here for the doc.
źródło
Hm. You have to specify window you clicked in
Mouse.GetPosition(IInputElement relativeTo)
Following code works well for meprotected 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.źródło