【问题标题】:WPF Storyboard can't resize window width with heightWPF Storyboard 无法随高度调整窗口宽度
【发布时间】:2017-08-08 16:29:44
【问题描述】:

我正在尝试使用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 以外的元素有关。

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    从 heightAnimation 中移除持续时间。

    【讨论】:

    • 谢谢:)。去掉 heightAnimaion 的持续时间确实会导致 2 个动画执行,但它们不会并行运行,所以宽度和高度会同时调整大小。当我删除持续时间时,窗口会调整其宽度和高度。
    • 你好,你不能动画宽度和高度平行,在这里你可以找到一个解决方法stackoverflow.com/questions/12332385/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-08
    • 1970-01-01
    • 2011-05-21
    • 1970-01-01
    • 2012-09-02
    • 2018-12-11
    • 1970-01-01
    相关资源
    最近更新 更多