21

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?

2 Answers 2

47

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.

3
  • will this work for DataGridCell (inside DataGrid wpf4)) too? apparently its not.
    – neebz
    Feb 23, 2011 at 20:34
  • @nEEbz: What do you mean? Do you want to move a DataGridCell relative to the main window?? I do not understand the relation to the original question. Please elaborate.
    – gehho
    Mar 3, 2011 at 13:02
  • see this > stackoverflow.com/questions/5096113/… . I have miserably failed to achieve this.
    – neebz
    Mar 3, 2011 at 17:35
3

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.