用户控件内的WPF动画

时间:2013-01-14 09:47:18

标签: wpf animation user-controls

我有一个用户控件,其作用类似于进度条,并将矩形的宽度设置为对事件的响应。有人生成具有特定%的事件,矩形宽度从其实际宽度动画到用户控件的actualWidth的%。

如果我尝试设置新的宽度,我得到" 调用线程无法访问此对象,因为另一个线程拥有它。"所以我使用Dispatcher.Invoke,它运行得很好。

如果我尝试设置宽度更改的动画而不是仅设置它,则会出现问题。然后,当使用调度程序时,我得到不同的线程拥有它错误事件。

因此。这段代码很好用:

bar.Dispatcher.Invoke((Action)delegate { bar.Width = myWidth; });

但是这段代码没有:

DoubleAnimation widthAnimation = new DoubleAnimation();
widthAnimation.From = bar.ActualWidth;
widthAnimation.To = myWidth;
widthAnimation.Duration = new Duration(new TimeSpan(0, 0, 0, 0, 500));
widthAnimation.RepeatBehavior = new RepeatBehavior(1);
bar.Dispatcher.Invoke( (Action)delegate {
    bar.BeginAnimation(Rectangle.WidthProperty, widthAnimation); 
});

那么..我如何在像这样的用户控件上运行动画?

提前致谢!!!

1 个答案:

答案 0 :(得分:1)

还应在UI线程中创建动画:

bar.Dispatcher.Invoke((Action)delegate
{
    var widthAnimation = new DoubleAnimation
    {
        From = bar.ActualWidth,
        To = myWidth,
        Duration = TimeSpan.FromMilliseconds(500)
    };
    bar.BeginAnimation(Rectangle.WidthProperty, widthAnimation); 
});