我有一个WPF窗口,由于SizeToContent =“ WidthAndHeight”,它会随着时间的推移更改其大小。最初,WindowStartupLocation =“ CenterScreen”显示了正确居中的窗口,然后我将其重新放置为:
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
但是当窗口先调整大小然后居中后,它会产生“跳跃”。
有什么办法可以顺利进行吗?
最佳答案
这对我有用:
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;
}