Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF - Set dialog window position relative to main window?

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?

like image 588
empo Avatar asked Mar 15 '10 11:03

empo


2 Answers

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.

like image 157
gehho Avatar answered Oct 21 '22 17:10

gehho


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

like image 36
Li3ro Avatar answered Oct 21 '22 18:10

Li3ro