获取wpf中窗口内元素的绝对位置

s3fp2yjn  于 2022-12-27  发布在  其他
关注(0)|答案(6)|浏览(158)

我想得到一个元素在被双击时相对于窗口/根元素的绝对位置。这个元素在它的父元素中的相对位置似乎是我能得到的全部,而我试图得到的是相对于窗口的点。我已经看到了如何在屏幕上得到一个元素的点的解决方案,而不是在窗口中。

jyztefdp

jyztefdp1#

我认为BrandonS想要的不是 mouse 相对于根元素的位置,而是某个后代元素的位置。
为此,有TransformToAncestor方法:

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

其中,myVisual是刚刚双击的元素,rootVisual是Application.Current.MainWindow或任何您想要的相对位置。

hmae6n7t

hmae6n7t2#

要获取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;
oxf4rvwz

oxf4rvwz3#

将此方法添加到静态类:

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以从应用程序窗口的左上角放置。

relj7zay

relj7zay4#

从.NET 3.0开始,您可以简单地使用*yourElement*.TranslatePoint(new Point(0, 0), *theContainerOfYourChoice*)
这将为您提供按钮的点0,0,但朝向容器。(您也可以提供另一个点0,0)
Check here for the doc.

guykilcj

guykilcj5#

childObj.MouseDown += (object sender, MouseButtonEventArgs e) =>
{
    Vector parent = (Vector)e.GetPosition(parentObj);
    Vector child = (Vector)e.GetPosition(childObj); // sender
    Point childPosition = (Point)(parent - child);
};
czq61nw1

czq61nw16#

你必须指定你在Mouse.GetPosition(IInputElement relativeTo)中点击的窗口下面的代码对我来说很好用

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

我怀疑你需要引用窗口不是从它自己的类,而是从应用程序的其他点。在这种情况下,Application.Current.MainWindow将帮助你。

相关问题