Этот код работает, если вы не хотите использовать свойство WindowStartupLocation в 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);
}
}
Я использую "screen.WorkingArea", потому что панель задач делает mainWindow меньше.Если вы хотите разместить окно посередине экрана, вместо него можно использовать «screen.Bounds».