WPF Storyboard无法使用高度调整窗口宽度

时间:2017-08-08 16:29:44

标签: c# wpf

我正在尝试使用Storyboard调整WPF窗口的大小。当我为窗口宽度或高度设置动画时,我的代码工作得很好,但是当我在两个窗口上应用故事板时,它只会动画第一个属性(在我的情况下为宽度)并跳过第二个属性。

我的代码是:

    private void AnimateWindowSize(double width, double height, bool isRelative = false)
    {
        //---------------------------------------------------
        //  Settings
        //---------------------------------------------------

        var duration = TimeSpan.FromSeconds(0.2);
        var newWidth = isRelative ? this.Width - width : width;
        var newHeight = isRelative ? this.Height - height : height;

        Console.WriteLine($"Animating window from {this.Width}x{this.Height} to {newWidth}x{newHeight}");

        this.Dispatcher.BeginInvoke(new Action(() =>
        {
            var storyboard = new Storyboard();

            //---------------------------------------------------
            //  Animate Width
            //---------------------------------------------------
            var widthAnimation = new DoubleAnimation()
            {
                Duration = new Duration(duration),
                From = this.ActualWidth,
                To = newWidth
            };

            Storyboard.SetTarget(widthAnimation, this);
            Storyboard.SetTargetProperty(widthAnimation, new PropertyPath(Window.WidthProperty));
            storyboard.Children.Add(widthAnimation);

            //---------------------------------------------------
            //  Animate Width
            //---------------------------------------------------
            var heightAnimation = new DoubleAnimation()
            {
                Duration = new Duration(duration),
                From = this.ActualHeight,
                To = newHeight
            };

            Storyboard.SetTarget(heightAnimation, this);
            Storyboard.SetTargetProperty(heightAnimation, new PropertyPath(Window.HeightProperty));
            storyboard.Children.Add(heightAnimation);

            //---------------------------------------------------
            //  Play
            //---------------------------------------------------
            //storyboard.Begin();
            this.BeginStoryboard(storyboard, HandoffBehavior.SnapshotAndReplace, false);
        }), null);
    }

顺便说一句,我已经创建了这种方法的通用版本,用于动画我的菜单等大小,并且它完美地运行。这似乎只是Window动画的一个问题。有谁知道如何修复它并应用窗口宽度和高度的动画?我在SO中的答案后跟着,但所有这些都与Window之外的元素有关。

1 个答案:

答案 0 :(得分:0)

从heightAnimation中删除持续时间。