我的wpf动画代码有什么问题

时间:2016-05-23 08:42:55

标签: c# wpf animation repeat

我希望多次重复我的动画,每次目标的属性随着触发或动画完成而改变。

但是这种情绪只是第一次起作用。

为了简化这一点,我只是让一个矩形在画布中从0移动到400,持续10次。代码被遵循。

我搜索了类似' wpf重复动画'等建议使用seek()方法或rect.BeginAnimation(property, null)的问题,但对我来说并不起作用。

private void init()
{
    Rectangle rect = new Rectangle();
    this.RegisterName("rect", rect);
    rect.Height = 100;
    rect.Width = 50;
    rect.Fill = Brushes.LightBlue;
    Canvas.SetTop(rect, 0);
    Canvas.SetLeft(rect, 0);
    myCanvas.Children.Add(rect);

    TargetAnimation(0);
}

private void TargetAnimation(int i)
{
    DoubleAnimation da = new DoubleAnimation();
    da.From = 0;
    da.To = 400;
    da.Duration = TimeSpan.FromSeconds(5);

    Storyboard.SetTargetName(da, "rect");
    Storyboard.SetTargetProperty(da, new PropertyPath(Canvas.LeftProperty));
    Storyboard storyboard = new Storyboard();
    storyboard.Children.Add(da);
    storyboard.Completed += Storyboard_Completed;
    storyboard.Begin(this);

}

private void Storyboard_Completed(object sender, EventArgs e)
{
    if (i < 10)
        TargetAnimation(++i);
    else
        return;
}

3 个答案:

答案 0 :(得分:3)

您应该在调用begin语句之前先注册已完成的事件 像这样:

storyboard.Completed += Storyboard_Completed;
 storyboard.Begin(this);

答案 1 :(得分:2)

我认为你误解了StoryBoard.Completed。您应该在da.Completed上应用委托。

&#13;
&#13;
        private void TargetAnimation(int i)
        {
            DoubleAnimation da = new DoubleAnimation();
            da.From = 0;
            da.To = 400;
            da.Duration = TimeSpan.FromSeconds(5);
            da.Completed += Storyboard_Completed;
            Storyboard.SetTargetName(da, "rect");
            Storyboard.SetTargetProperty(da, new PropertyPath(Canvas.LeftProperty));
            Storyboard storyboard = new Storyboard();
            storyboard.Children.Add(da);
            storyboard.Begin(this);
            //storyboard.Completed += Storyboard_Completed;
        }
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您已将i作为参数传递,但未使用它或其值来确定。 所以你必须使用if语句来限制TargetAnimation(int i)值,该语句等于目标动画值i