Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep window centered after SizeToContent smoothly

I have a WPF window that changes it's size over time due to SizeToContent="WidthAndHeight". Initially the WindowStartupLocation="CenterScreen" shows the window centered correctly, and after that I recenter it with:

Private Sub Window_SizeChanged(ByVal sender As Object, ByVal e As System.Windows.SizeChangedEventArgs) Handles Me.SizeChanged
  Me.Top = (SystemParameters.WorkArea.Height - e.NewSize.Height) / 2
  Me.Left = (SystemParameters.WorkArea.Width - e.NewSize.Width) / 2
End Sub

But it produces a "jump" as the window is resized first and centered after.

Is there any way of doing it smoothly?

like image 902
user1416197 Avatar asked May 09 '13 06:05

user1416197


1 Answers

This worked for me:

protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
{
    base.OnRenderSizeChanged(sizeInfo);

    //Calculate half of the offset to move the form

    if (sizeInfo.HeightChanged)
        this.Top += (sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height) / 2;

    if (sizeInfo.WidthChanged)
        this.Left += (sizeInfo.PreviousSize.Width - sizeInfo.NewSize.Width) / 2;
}
like image 168
Imran Rashid Avatar answered Nov 13 '22 09:11

Imran Rashid