【问题标题】:WPF - Set dialog window position relative to main window?WPF - 设置对话框窗口相对于主窗口的位置?
【发布时间】:2011-01-27 15:27:58
【问题描述】:

我只是在创建自己的 AboutBox,并使用 Window.ShowDialog() 调用它

如何让它相对于主窗口定位,即距离顶部 20 像素并居中?

【问题讨论】:

    标签: wpf position window


    【解决方案1】:

    我会采用手动方式,而不是依靠 WPF 为我进行计算..

    System.Windows.Point positionFromScreen = this.ABC.PointToScreen(new System.Windows.Point(0, 0));
    PresentationSource source = PresentationSource.FromVisual(this);
    System.Windows.Point targetPoints = source.CompositionTarget.TransformFromDevice.Transform(positionFromScreen);
    
    AboutBox.Top = targetPoints.Y - this.ABC.ActualHeight + 15;
    AboutBox.Left = targetPoints.X - 55;
    

    ABC 是父窗口中的一些 UIElement(如果你愿意,可以是 Owner..),也可以是窗口本身(左上角)..

    祝你好运

    【讨论】:

      【解决方案2】:

      您可以简单地使用Window.LeftWindow.Top 属性。从主窗口读取它们并将值(加上 20 px 或其他值)分配给 AboutBox 调用 ShowDialog() 方法之前。

      AboutBox dialog = new AboutBox();
      dialog.Top = mainWindow.Top + 20;
      

      要使其居中,您也可以简单地使用WindowStartupLocation 属性。将此设置为WindowStartupLocation.CenterOwner

      AboutBox dialog = new AboutBox();
      dialog.Owner = Application.Current.MainWindow; // We must also set the owner for this to work.
      dialog.WindowStartupLocation = WindowStartupLocation.CenterOwner;
      

      如果您希望它水平居中,而不是垂直居中(即固定垂直位置),则必须在加载 AboutBox 后在 EventHandler 中执行此操作,因为您需要根据 Width 计算水平位置AboutBox,只有在加载后才知道。

      protected override void OnInitialized(...)
      {
          this.Left = this.Owner.Left + (this.Owner.Width - this.ActualWidth) / 2;
          this.Top = this.Owner.Top + 20;
      }
      

      呸呸呸。

      【讨论】:

      • 这也适用于 DataGridCell(DataGrid wpf4 内部))吗?显然不是。
      • @nEEbz:你什么意思?你想移动一个DataGridCell 相对于主窗口吗?我不明白与原始问题的关系。请详细说明。
      • 看到这个 > stackoverflow.com/questions/5096113/… 。我可悲地没能做到这一点。
      猜你喜欢
      • 1970-01-01
      • 2017-09-06
      • 2017-10-22
      • 1970-01-01
      • 2013-07-10
      • 1970-01-01
      • 2016-04-02
      • 2013-01-05
      • 2012-11-27
      相关资源
      最近更新 更多