Click here to Skip to main content
Click here to Skip to main content

WPF: Center Child Window

By , 15 Jun 2009
 

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.

<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.

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.

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

License

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

About the Author

mastermel
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5 Pinmemberdkatubulla5 Aug '12 - 23:48 
GeneralFor a user control to display window center Pinmemberralfelt25 Mar '11 - 10:17 
GeneralMy vote of 1 PinmemberKavan Shaban15 Jun '09 - 17:41 

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

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 15 Jun 2009
Article Copyright 2009 by mastermel
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid