由于SizeToContent =“WidthAndHeight”,我有一个WPF窗口随时间改变它的大小。最初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
但它会产生一个“跳跃”,因为窗口首先调整大小并居中。
有没有办法顺利完成?
答案 0 :(得分:3)
这对我有用:
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;
}
答案 1 :(得分:0)
您可以使用TranslateTransform为位置更改设置动画,而不是直接设置Me.Top和Me.Left。
public static void MoveTo(this UIElement target, double newX, double newY)
{
var top = Canvas.GetTop(target);
var left = Canvas.GetLeft(target);
TranslateTransform trans = new TranslateTransform();
target.RenderTransform = trans;
DoubleAnimation anim1 = new DoubleAnimation(top, newY - top, TimeSpan.FromSeconds(10));
DoubleAnimation anim2 = new DoubleAnimation(left, newX - left, TimeSpan.FromSeconds(10));
trans.BeginAnimation(TranslateTransform.XProperty,anim1);
trans.BeginAnimation(TranslateTransform.YProperty,anim2);
}
代码来源:WPF. Easiest way to move Image to (X,Y) programmatically?
答案 2 :(得分:0)
感谢您发布此信息。我的情况是我有一个对话框窗口,该对话框窗口在加载ViewModel
时会调整大小,并指定其高度和宽度。我使用了您的示例,但对其进行了一些修改,以捕获所有者窗口,然后再更新。
protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
{
base.OnRenderSizeChanged(sizeInfo);
//Calculate half of the owner to move the form
Window owner = Owner as Window;
this.Top = (owner.Height / 2) - (this.Height / 2);
this.Left = (owner.Width / 2) - (this.Width / 2);
}
答案 3 :(得分:-1)
private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
{
if (e.HeightChanged)
Top += (e.PreviousSize.Height - e.NewSize.Height) / 2;
if (e.WidthChanged)
Left += (e.PreviousSize.Width - e.NewSize.Width) / 2;
}