12

由于 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

但它会产生一个“跳跃”,因为窗口首先调整大小并居中。

有什么方法可以顺利完成吗?

4

4 回答 4

8

这对我有用:

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;
}
于 2015-04-23T11:55:21.023 回答
0

除了直接设置 Me.Top 和 Me.Left 之外,您还可以使用 TranslateTransform 来设置位置变化的动画。

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。以编程方式将图像移动到 (X,Y) 的最简单方法?

于 2013-11-11T14:34:57.793 回答
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);
}
于 2018-08-28T18:57:53.427 回答
-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;
    }
于 2019-06-12T14:57:14.810 回答