WPF : How to set a Dialog position to show at the center of the application?

You can try to get a hold of the MainWindow in the Loaded event like this

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    Application curApp = Application.Current;
    Window mainWindow = curApp.MainWindow;
    this.Left = mainWindow.Left + (mainWindow.Width - this.ActualWidth) / 2;
    this.Top = mainWindow.Top + (mainWindow.Height - this.ActualHeight) / 2;
}

I think it's easier to use xaml markup

<Window WindowStartupLocation="CenterOwner">

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)
{
    ...

Tags:

Wpf

Dialog