Click here to Skip to main content
15,880,543 members
Articles / Desktop Programming / WPF

WPF: Center Child Window

Rate me:
Please Sign up or sign in to vote.
4.43/5 (11 votes)
15 Jun 2009CPOL 63.7K   6   4
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();
This article was originally posted at http://mel-green.com?p=326

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
JasRaj Bishnoi27-Jun-13 0:06
JasRaj Bishnoi27-Jun-13 0:06 
GeneralMy vote of 5 Pin
dkatubulla5-Aug-12 23:48
dkatubulla5-Aug-12 23:48 
GeneralFor a user control to display window center Pin
remy_25-Mar-11 10:17
remy_25-Mar-11 10:17 
GeneralMy vote of 1 Pin
Kavan Shaban15-Jun-09 17:41
Kavan Shaban15-Jun-09 17:41 
Where's the code!

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.