A. Medvedev
A. Medvedev

Reputation: 25

Center dynamic size window in parent window

PROBLEM

Because of child window dynamic size, the property WindowStartupLocation is not working well enough. It puts the child window in center, but after that, child window changes its size and starts to "pop out" from the bottom of the main window.

QUESTION

How to put the child window of the parent window in the center, taking into account that the child window has a dynamic size?

Code example:
var window = new WindowDialog(MainWindow, "Title", new DialogAgent(), false)
            {
                WindowStartupLocation = WindowStartupLocation.CenterOwner,
                SizeToContent = SizeToContent.Height,
                ShowInTaskbar = false
            };

Upvotes: 0

Views: 1488

Answers (1)

Francois Borgies
Francois Borgies

Reputation: 2408

You can try something like this :

ChildWindow cw = new ChildWindow();
cw.ShowInTaskbar = false;
cw.Owner = Application.Current.MainWindow;
cw.Show();

And in the XAML's child windows :

WindowStartupLocation="CenterScreen" 

You can try to center the windows with a simple method to recalculate the position of your Window according to the Owner windows and call this method at the end of your Loaded event, like this (Here for the discuss) :

private void CenterOwner()
{
    if (Owner != null)
    {
        double top = Owner.Top + ((Owner.Height - this.ActualHeight) / 2);
        double left = Owner.Left + ((Owner.Width - this.ActualWidth) / 2);

        this.Top = top < 0 ? 0 : top;
        this.Left = left < 0 ? 0 : left;
    }
}

Upvotes: 1

Related Questions