当双击某个元素时,我想获得该元素相对于窗口/根元素的绝对位置。元素在其父元素中的相对位置似乎是我所能得到的全部,而我想要得到的是相对于窗口的点。我已经看到了如何在屏幕上获得元素的点的解决方案,但不是在窗口中。
发布于 2013-03-21 08:31:33
要获取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;
发布于 2014-01-29 00:59:48
将此方法添加到静态类:
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
,以便从应用程序窗口的左上角放置。
发布于 2018-07-22 19:44:18
从.NET 3.0开始,您可以简单地使用*yourElement*.TranslatePoint(new Point(0, 0), *theContainerOfYourChoice*)
。
这将给你的按钮的点0,0,但指向容器。(你也可以给出另外一个点,0,0)
https://stackoverflow.com/questions/386731
复制相似问题