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 = ??
}
}
This code works if you don't want to use the WindowStartupLocation property in xaml:
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.
If you have little control over the windows which you need to show, the following snippet may be useful
For the sake of documentation, I'll add here an example of how I achieved something similar. What I needed was a popup that covered the entire parent Window content area (excluding the title bar), but simply centering the dialog and stretching its content didn't work because the dialog was always offset a little bit from the bottom.
Note about user experience: It's not nice not being able to drag/close the parent window when the borderless dialog is showing, so I would reconsider using it. I also decided not to do this after posting this answer, but will leave it up for others to look at.
After some googling and testing, I finally managed to do it like this:
The
DialogWindow
is a Window and its owner is set to the main application Window. TheWindowStartupLocation
must be set toManual
for manual positioning to work.Result:
I don't know if there's an easier way to do this, but nothing else seemed to work for me.
In the XAML belonging to the Dialog:
and in C# when you instantiate the Dialog:
I'd like to add to the Fredrik Hedblad response that if the MainWindows has been resized or maximized, the result would be wrong, because mainWindow.Width and mainWindow.Height reflect the value that are set on the XAML.
If you want the actual values, you can use mainWindow.ActualWidth and mainWindow.ActualHeight:
You can try to get a hold of the MainWindow in the Loaded event like this