【发布时间】: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";
【问题讨论】: