Wpf center child window not working with sizetocontent

sizetocontentwpf

If i set SizeToContent to WidthAndHeight, then WindowStartupLocation="CenterOwner" does not work properly. Instead of the center of the new window to be at the center of its parent owner, it looks more like the top left hand corner of the child window to be at the center of the parent.
If i remove SizeToContent then all is ok.
What is wrong?

Best Solution

Well, Ray has put this up brilliantly. In simple terms, what he wants to say is, that you are setting the content of your controls in your Loaded event, which resets the Height & Width (and also the ActualHeight & ActualWidth) after the positioning of the window is done.

To fix this, you have two alternatives:

  1. Move your content value setting code to the constructor, or,
  2. Add a simple method to recalculate the position of your Window according to the Owner and call this method at the end of your Loaded event, like this:

...

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;
    }
}
Related Question