WPF - Set dialog box position relative to main window?

I just create my own AboutBox and call it using Window.ShowDialog ()

How can I position it relative to the main window, that is, 20 pixels above and in the center?

+19
wpf window position relative
Mar 15 '10 at 11:08
source share
2 answers

You can simply use the Window.Left and Window.Top properties. Read them from the main window and assign values ​​(plus 20 pixels or something else) to the AboutBox before by calling the ShowDialog() method.

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

To focus on it, you can also just use the WindowStartupLocation property. Set it 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. a fixed vertical arrangement), you will need to do this in the EventHandler after loading the AboutBox, because you will need to calculate the horizontal position depending on the width ofBox. and this is known only after it has been downloaded.

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

gehho.

+39
Mar 15 '10 at 11:28
source share

I would go in a manual way rather than counting on WPF to do 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 in the parent window (maybe if you want ...), and it can also be the window itself (top left point) ..

Good luck.

+2
Dec 02 '15 at 9:47
source share



All Articles