【问题标题】:Synchronous / blocking animations in WPF?WPF中的同步/阻塞动画?
【发布时间】:2010-08-06 03:56:30
【问题描述】:

我迫切需要 C#/WPF 中的同步/阻塞动画(不幸的是,在完成事件中执行代码对我来说还不够)。

我尝试了两种方法:

1) 使用 BeginAnimation 启动(异步)动画,持续时间为 x。 在异步调用之后添加 Thread.Sleep(x)。但是这不起作用,动画在线程休眠给定持续时间后启动。

2) 使用信号(AutoResetEvent 类):在另一个线程中启动动画,animations completed 事件表明动画已使用信号完成。结果:代码永远不会执行,整个线程被阻塞,没有动画显示/启动,尽管锁定的代码在 BeginAnimation 调用之后开始。也许我以错误的方式使用信号? (我以前从未使用过它们)。 (基于此线程的想法:WPF: Returning a method AFTER an animation has completed

您可以在http://cid-0432ee4cfe9c26a0.office.live.com/self.aspx/%C3%96ffentlich/BlockingAnimation.zip找到示例项目

非常感谢您的帮助!

顺便说一句,这是纯代码:

方法一:

messageLogTB.Clear();

TranslateTransform translateTransform = new TranslateTransform();
animatedButton.RenderTransform = translateTransform;

DoubleAnimation animation = new DoubleAnimation(0, 200.0, new Duration(TimeSpan.FromMilliseconds(2000)));
translateTransform.BeginAnimation(TranslateTransform.XProperty, animation);

// Animation is asynchronous and takes 2 seconds, so lets wait two seconds here
// (doesn't work, animation is started AFTER the 2 seconds!)
Thread.Sleep(2000);
messageLogTB.Text += "animation complete";

方法二:

messageLogTB.Clear();

TranslateTransform translateTransform = new TranslateTransform();
animatedButton.RenderTransform = translateTransform;

AutoResetEvent trigger = new AutoResetEvent(false);

// Create the animation, sets the signaled state in its animation completed event
DoubleAnimation animation = new DoubleAnimation(0, 200.0, new Duration(TimeSpan.FromMilliseconds(2000)));
animation.Completed += delegate(object source, EventArgs args) 
    {
        trigger.Set();
        messageLogTB.Text += "\nsignaled / animation complete";
    };


// Start the animation on the dispatcher
messageLogTB.Text += "starting animation";

Dispatcher.Invoke(
new Action(
    delegate()
    {
        translateTransform.BeginAnimation(TranslateTransform.XProperty, animation);
    }
), null);

// Wait for the animation to complete (actually it hangs before even starting the animation...)
trigger.WaitOne();
messageLogTB.Text += "\nThis should be reached after the signal / animation";

【问题讨论】:

    标签: c# wpf animation


    【解决方案1】:

    停止使用线程使其变得复杂。使用 Animation 的 Completed 事件,而不是在单个序列中链接多个动画或在 Completed 事件中执行一些代码。

    【讨论】:

      【解决方案2】:

      诀窍是在单独的 UI 线程上运行动画(这意味着为该线程设置一个消息循环,并记住在完成后将其拆除)。

      我刚刚发布了blog post,描述了我是如何做到这一点的。

      【讨论】:

      • +1 用于回答问题 ;-) 之前找到您的博文,我需要在 Silverlight 中实现此功能以使用此方法模拟 DependencyObject.SetCurrentValue:stackoverflow.com/questions/3247008/… 以解决此问题:@ 987654323@ ...说起来容易做起来难! ..
      【解决方案3】:

      您可能想要发布您正在尝试完成的内容的上下文,因为您所描述的内容在 WPF 中是不可能的。动画在 UI 线程上运行,如果你阻塞 UI 线程,动画就不会发生。

      【讨论】:

        猜你喜欢
        • 2018-04-06
        • 1970-01-01
        • 2023-03-14
        • 2013-07-20
        • 2017-08-13
        • 1970-01-01
        • 2014-02-02
        • 2013-05-07
        相关资源
        最近更新 更多