如何在wpf中计算弹出控件和屏幕顶部之间的距离?

问题描述 投票:1回答:2

我们使用WPF弹出控件。

我们需要知道如何从屏幕顶部计算Popup控件的距离/高度或Y坐标。那么,如何计算呢?

有关问题截图,请参阅附图。

Image for pop up with the issue

我尝试了两种解决方案如下:

第一个解决方案------------------------------------------------ -------

Window w = Application.Current.Point 
relativePoint = popNonTopMostPopup.TransformToAncestor(w)
                             .Transform(new Point(0, 0));

问题:始终返回与relativePoint.X = 3.0和relativePoint.Y = 25.96相同的坐标 我的弹出窗口打开在地图图标的右侧,如图像所示...所以当我点击不同的地图图标时,弹出位置会相应地改变。所以它应该返回不同的geo-coordnates。

第二种解决方案------------------------------------------------ ----

Point position = popNonTopMostPopup.PointToScreen(new Point(0d, 0d)),
controlPosition = this.PointToScreen(new Point(0d, 0d));
position.X -= controlPosition.X;
position.Y -= controlPosition.Y;

问题:此解决方案也存在同样的问题..每次位置时总是返回相同的地理坐标.X = 3.0和position.Y = 49.0

c# .net popup wpf-controls wpf-positioning
2个回答
0
投票

你可以用这个:

TransformToAncestor,如here所示。

Point relativePointInWindow = yourPopup.TransformToAncestor(yourWindow)
                                       .Transform(new Point(0, 0));

即使在UserControl,你也可以访问父母

popup.parent.parent    
popup => usercontrol => window

否则你可以使用Application.Current.MainWindow来获得你的MainWindow。

然后你去获取弹出窗口的位置,如上图所示。

如果需要,您可以将System.Windows.SystemParameters.CaptionHeight添加到结果中。

这看起来与此类似(未经测试):

public class MyMapArea : UserControl
{
    public MyMapArea()
    {

    }

    /// <summary>
    /// Returns the Y position relative to ScreenTop in Pixels
    /// </summary>
    private int GetYPositionOfPopup()
    {
        Popup popup = this.popup;

        Window window;

        FrameworkElement element;

        //Walk up the ui tree
        while(1 == 1)
        {
            //Remember to check for nulls, etc...
            element = this.parent;
            if(element.GetType() == typeof(Window))
            {
                //if you found the window set it to "window"
                window = (window)element;
                break;
            }
        }

        Point relativePointInWindow = popup.TransformToAncestor(window)
                                   .Transform(new Point(0, 0));

        return relativePointInWindow.Y // + System.Windows.SystemParameters.CaptionHeight;
    }
}

0
投票

以下逻辑可以计算弹出窗口内控件的位置。它可以在显示弹出窗口后进行计算(否则源将为null)。

当您显示弹出窗口的内容时,您位于不同的可视树中,因此无需使用原始Popup对象进行任何计算。

var source = PresentationSource.FromVisual(controlInsidePopup);
if (source == null)
  return;

// Get absolute location on screen of upper left corner of the control
var locationFromScreen = controlInsidePopup.PointToScreen(new Point(0, 0));

var targetPoints = source.CompositionTarget.TransformFromDevice.Transform(locationFromScreen);

string positionInfo = $"Current Position X: {targetPoints.X}, Y: {targetPoints.Y}";

代码是从这里采取的略微修改的逻辑:https://social.msdn.microsoft.com/Forums/vstudio/en-US/281a8cdd-69a9-4a4a-9fc3-c039119af8ed/absolute-screen-coordinates-of-wpf-user-control?forum=wpf

© www.soinside.com 2019 - 2024. All rights reserved.