Search code examples
c#wpfposition

When does WindowStartupLocation take effect


When does in WPF takes this.WindowStartupLocation = WindowStartupLocation.CenterOwner; effect?

I want this as the default behaviour but if some window-layout information exists (Top, Left, ...), i want to set them in the Loaded event of the window. But this does not work correctly.

If i comment out WindowStartupLocation, it works.

Maybe some one solve this problem before. Thank you!


Solution

  • WindowStartupLocation takes effect and set the window in the center at the start up only, so once your window is set up it cannot take any other effect on resizing or moving the window.

    The MSDN says:

    Gets or sets the position of the window when first shown.

    Also see this MSDN blog where it suggests how you can hook up it as the default behavior:

    private void SizeChangedHandler(Object sender, SizeChangedEventArgs e)
    {
        Rect workArea = SystemParameters.WorkArea;
        this.Left = (workArea.Width - this.ActualWidth) / 2;
        this.Top = (workArea.Height - this.ActualHeight) / 2;
    }
    
    private void LocationChangedHandler(Object sender, EventArgs e)
    {
        Rect workArea = SystemParameters.WorkArea;
        this.Left = (workArea.Width - this.ActualWidth) / 2;
        this.Top = (workArea.Height - this.ActualHeight) / 2;
    }