ShowDialog and centering the window

I was using ShowDialog to show a Xaml window and was surprised to find that it wasn’t easy to get it to center on the calling Window. Setting the WindowStartupLocation property to CenterOwner did not seem to have much effect. That’s when I realized that the Owner has to be explicitly set. Now, I was calling ShowDialog from a Grid which was at least 5-6 levels nested in a parent Window, so I had to find the closest ancestor window that was a Window object. The code’s simple but I thought if anyone else wanted to center a dialog on screen, he could reuse this code. For all I know there might be an easier way to do this – probably some property or method that I missed. If so please let me know via a comment, so I can feel like an idiot. 🙂

DialogWin dwin = new DialogWin();

FrameworkElement fwElem = this;
while(!(fwElem is Window))
{
	if (!(fwElem is FrameworkElement))
		break;
	fwElem = fwElem.Parent as FrameworkElement;
}
if (fwElem is Window)
{
	dwin.WindowStartupLocation = WindowStartupLocation.CenterOwner;
	dwin.Owner = fwElem as Window;
}

dwin.ShowDialog();
Advertisements

2 thoughts on “ShowDialog and centering the window

  1. Hi Nish

    I had a similar problem, in that I have a WPF UserControl,
    which is runtime injected into a modal window.
    Clicking a button within the control closes the window, which ment I had to find the Window.

    There is a static method on the Window object that can do this for you, given a DP as a parameter.

    I would expect this would eleminiate your requirement for a loop.

    Window w = Window.GetWindow(this);

  2. Paul,
    Excellent work, didn’t realise the function existed.

    In VB.net

    ‘ LL: WPF nested controls require you to identify the parent window, so the startuplocation can be set properly.
    .Owner = Window.GetWindow(Me)
    .WindowStartupLocation = WindowStartupLocation.CenterOwner
    .ShowDialog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s