WPF中的同步/阻止动画?

问题描述:

我非常需要C#/ WPF中的同步/阻塞动画(在完成的事件中执行代码不幸,在我的情况下是不够的)。WPF中的同步/阻止动画?

我尝试了两种方式:

1)开始使用BeginAnimation与x的持续时间的(异步)动画。 在异步调用后添加Thread.Sleep(x)。然而,这不起作用,动画在线程休眠了给定的持续时间后开始。

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

您可以在http://cid-0432ee4cfe9c26a0.office.live.com/self.aspx/%C3%96ffentlich/BlockingAnimation.zip

找到一个样本项目非常感谢您的帮助!

顺便说一句,这里的明码:

方法1:

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"; 

方法2:

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"; 

停止使其复杂与线程。使用Animation的Completed事件可以将单个序列中的多个动画链接起来,也可以在Completed事件中执行一些代码。

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

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

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

+0

+1用于回答问题;-)找到您的博客文章之前,我需要在Silverlight中实现此模拟使用此方法的DependencyObject.SetCurrentValue:http://*.com/questions/3247008/silverlight-dependencyproperty- setcurrentvalue相当于为了解决这个问题:http://*.com/questions/13181788/wpf-dependency-property-precedence-reference-type-default-values#comment17945942_13181788 ...它说起来容易做起来难! .. – 2012-11-01 21:46:47