WPF - Set dialog window position relative to main window?

≯℡__Kan透↙ 提交于 2019-12-09 02:14:47

问题


I'm just creating my own AboutBox and I'm calling it using Window.ShowDialog()

How do I get it to position relative to the main window, i.e. 20px from the top and centered?


回答1:


You can simply use the Window.Left and Window.Top properties. Read them from your main window and assign the values (plus 20 px or whatever) to the AboutBox before calling the ShowDialog() method.

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

To have it centered, you can also simply use the WindowStartupLocation property. Set this to 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;

If you want it to be centered horizontally, but not vertically (i.e. fixed vertical location), you will have to do that in an EventHandler after the AboutBox has been loaded because you will need to calculate the horizontal position depending on the Width of the AboutBox, and this is only known after it has been loaded.

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

gehho.




回答2:


I would go the manual way, instead of count on WPF to make the calculation for me..

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;

Where ABC is some UIElement within the parent window (could be Owner if you like..) , And could also be the window itself (top left point)..

Good luck



来源:https://stackoverflow.com/questions/2446602/wpf-set-dialog-window-position-relative-to-main-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!