How to set Dialog\'s position that came from .ShowDialog();
to show at the center of the mainWindows.
This is the way I try to set position.
This code works if you don't want to use the WindowStartupLocation property in xaml:
private void CenterWindowOnApplication()
{
System.Windows.Application curApp = System.Windows.Application.Current;
Window mainWindow = curApp.MainWindow;
if (mainWindow.WindowState == WindowState.Maximized)
{
// Get the mainWindow's screen:
var screen = System.Windows.Forms.Screen.FromRectangle(new System.Drawing.Rectangle((int)mainWindow.Left, (int)mainWindow.Top, (int)mainWindow.Width, (int)mainWindow.Height));
double screenWidth = screen.WorkingArea.Width;
double screenHeight = screen.WorkingArea.Height;
double popupwindowWidth = this.Width;
double popupwindowHeight = this.Height;
this.Left = (screenWidth / 2) - (popupwindowWidth / 2);
this.Top = (screenHeight / 2) - (popupwindowHeight / 2);
}
else
{
this.Left = mainWindow.Left + ((mainWindow.ActualWidth - this.ActualWidth) / 2;
this.Top = mainWindow.Top + ((mainWindow.ActualHeight - this.ActualHeight) / 2);
}
}
I am using "screen.WorkingArea" because the task bar makes the mainWindow smaller. If you want to place the window in the middle of the screen, you can use "screen.Bounds" instead.
In the XAML belonging to the Dialog:
<Window ... WindowStartupLocation="CenterOwner">
and in C# when you instantiate the Dialog:
MyDlg dlg = new MyDlg();
dlg.Owner = this;
if (dlg.ShowDialog() == true)
{
...