【问题标题】:How can I pause a storyboard?如何暂停情节提要?
【发布时间】:2011-03-15 08:33:15
【问题描述】:

这看起来应该很容易,但我无法让 WPF 故事板暂停。我调用了 Pause,但没有任何反应——它继续制作动画。

这是一个复制案例:一个按钮,它的宽度动画。如果单击该按钮,它会在情节提要上调用暂停。我希望,一旦我单击按钮,它的宽度应该停止变化;相反,它的宽度保持正确的动画效果,就好像我从未调用过暂停一样。

NameScope.SetNameScope(this, new NameScope());
var storyboard = new Storyboard();

var button = new Button { Content = "Pause", Name = "pause" };
this.Content = button;
RegisterName(button.Name, button);
var animation = new DoubleAnimation(0, 200, TimeSpan.FromSeconds(5));
Storyboard.SetTargetName(animation, button.Name);
Storyboard.SetTargetProperty(animation,
    new PropertyPath(FrameworkElement.WidthProperty));
storyboard.Children.Add(animation);

button.Click += (sender, e) => { storyboard.Pause(this); };
storyboard.Begin(this);

根据我对文档的理解,我应该使用传递给Begin 的相同参数调用Pause(FrameworkElement) 重载,因此是上面的Pause(this)。但我也试过storyboard.Pause(),行为没有改变。我还尝试了storyboard.Pause(button),只是为了它,再次没有效果。我会尝试 storyboard.Pause(storyboard)storyboard.Pause(animation) 只是为了用尽可能性,但没有一个编译 - 它想要一个 FrameworkElement(或 FrameworkContentElement)。

如何让故事板暂停?

【问题讨论】:

    标签: wpf animation storyboard


    【解决方案1】:

    我不知道你为什么使用那个奇怪的 SetNameScope 等。清除你的代码我可以让它工作:

            //NameScope.SetNameScope(this, new NameScope());
            var storyboard = new Storyboard();
    
            var button = new Button { Content = "Pause", Name = "pause" };
            this.Content = button;
            //RegisterName(button.Name, button);
            var animation = new DoubleAnimation(0, 200, TimeSpan.FromSeconds(5));
            Storyboard.SetTarget(animation, button);
            Storyboard.SetTargetProperty(animation,
                new PropertyPath(FrameworkElement.WidthProperty));
            storyboard.Children.Add(animation);
    
            button.Click += (sender, e) => { storyboard.Pause(); };
            storyboard.Begin();
    

    【讨论】:

    • 嗯。 MSDN 文档坚持您必须设置名称范围,但您的版本 (a) 更简单并且 (b) 有效。我会接受的。
    • 我不得不说我有点困惑......我已经编写 WPF 5 年了,这是我第一次看到 NameScope 和 RegisterName 的用法...... :-/
    • 看起来代码更改的神奇组合是 (a) 使用 SetTarget 而不是 SetTargetName,以及 (b) 使用无参数 BeginPause 而不是传递 this。 NameScope 是无害的,但在使用 SetTarget 时是不必要的。
    • 是的,好吧...我刚刚删除了我从不使用的所有东西,它起作用了 ;-)
    • 坚持使用 NameScope / RegisterName 的文档在这里:“Storyboards Overview”msdn.microsoft.com/en-us/library/ms742868.aspx。我不知道他们为什么这么说——我更喜欢你的版本。
    猜你喜欢
    • 2011-01-16
    • 1970-01-01
    • 1970-01-01
    • 2014-11-23
    • 2010-12-24
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    相关资源
    最近更新 更多