Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

WPF: Center Child Window

0.00/5 (No votes)
15 Jun 2009 1  
Here's a method I've found for centering a window to either its parent or the main window for the application, in WPF.

Here’s a method I’ve found for centering a window to either its parent or the main window for the application, in WPF. It’s not too different from how you do it in WinForms.

For the child window, set its WindowStartupLocation to “CenterOwner”. This will cause it to show in the center of the owning Window.

XML
<Window x:Class="WpfApplication1.TestChild"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="TestChild" Height="300" Width="300"
    WindowStartupLocation="CenterOwner">

Now, all that’s left to do is set its owner before displaying it. If the code you’re using to display the window is running inside of a Window class, then you can just use this.

C#
TestChild testWindow = new TestChild();
testWindow.Owner = this;
testWindow.Show();

This isn’t always the case, however; sometimes, you need to display the child window from the code running on a page or a user control. In this case, you want the child window to be centered to the main window of the application.

C#
TestChild testWindow = new TestChild();
testWindow.Owner = Application.Current.MainWindow;
testWindow.Show();

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here