我想在双击时获得与窗口/根元素相关的元素的绝对位置 . 元素在它的父元素中的相对位置是我可以看到的,而我想要达到的是相对于窗口的点 . 我已经看到了如何在屏幕上获取元素点的解决方案,但不是在窗口中 .
将此方法添加到静态类:
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); }
将 relativeToScreen 参数设置为 true ,从整个屏幕的左上角放置到 false ,以便从应用程序窗口的左上角放置 .
relativeToScreen
true
false
我知道这个问题很老,但是,从.NET 3.0开始,你可以简单地使用 *yourElement*.TranslatePoint(new Point(0, 0), *theContainerOfYourChoice*) .
*yourElement*.TranslatePoint(new Point(0, 0), *theContainerOfYourChoice*)
这将为您提供按钮的0,0点,但是朝向容器 . (你也可以给出0,0的另一点)
Check here for the doc.
要获得窗口中UI元素的绝对位置,您可以使用:
Point position = desiredElement.PointToScreen(new Point(0d, 0d));
如果您在用户控件中,并且只想在该控件中使用UI元素的相对位置,只需使用:
Point position = desiredElement.PointToScreen(new Point(0d, 0d)), controlPosition = this.PointToScreen(new Point(0d, 0d)); position.X -= controlPosition.X; position.Y -= controlPosition.Y;
嗯 . 您必须指定在 Mouse.GetPosition(IInputElement relativeTo) 中单击的窗口 . 以下代码适用于我
Mouse.GetPosition(IInputElement relativeTo)
protected override void OnMouseDown(MouseButtonEventArgs e) { base.OnMouseDown(e); Point p = e.GetPosition(this); }
我怀疑你需要从它自己的类而不是应用程序的其他方面引用窗口 . 在这种情况下 Application.Current.MainWindow 会帮助你 .
Application.Current.MainWindow
我认为BrandonS想要的不是鼠标相对于根元素的位置,而是一些后代元素的位置 .
为此,有TransformToAncestor方法:
Point relativePoint = myVisual.TransformToAncestor(rootVisual) .Transform(new Point(0, 0));
其中 myVisual 是刚刚双击的元素,而 rootVisual 是Application.Current.MainWindow或者你想要的位置相对于什么 .
myVisual
rootVisual
5 回答
将此方法添加到静态类:
将
relativeToScreen
参数设置为true
,从整个屏幕的左上角放置到false
,以便从应用程序窗口的左上角放置 .我知道这个问题很老,但是,从.NET 3.0开始,你可以简单地使用
*yourElement*.TranslatePoint(new Point(0, 0), *theContainerOfYourChoice*)
.这将为您提供按钮的0,0点,但是朝向容器 . (你也可以给出0,0的另一点)
Check here for the doc.
要获得窗口中UI元素的绝对位置,您可以使用:
如果您在用户控件中,并且只想在该控件中使用UI元素的相对位置,只需使用:
嗯 . 您必须指定在
Mouse.GetPosition(IInputElement relativeTo)
中单击的窗口 . 以下代码适用于我我怀疑你需要从它自己的类而不是应用程序的其他方面引用窗口 . 在这种情况下
Application.Current.MainWindow
会帮助你 .我认为BrandonS想要的不是鼠标相对于根元素的位置,而是一些后代元素的位置 .
为此,有TransformToAncestor方法:
其中
myVisual
是刚刚双击的元素,而rootVisual
是Application.Current.MainWindow或者你想要的位置相对于什么 .