WPF : How to set a Dialog position to show at the center of the application?
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.
private void Window_Loaded(object sender, RoutedEventArgs e)
{
PresentationSource source = PresentationSource.FromVisual(this);
if (source != null)
{
Left = ??
Top = ??
}
}
Solution 1:
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)
{
...
Solution 2:
I think it's easier to use xaml markup
<Window WindowStartupLocation="CenterOwner">
Solution 3:
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;
}
Solution 4:
Just in code behind.
public partial class CenteredWindow:Window
{
public CenteredWindow()
{
InitializeComponent();
WindowStartupLocation = WindowStartupLocation.CenterOwner;
Owner = Application.Current.MainWindow;
}
}