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

标签 c# wpf animation repeat

我想重复我的动画几次,每次目标的属性都会随着触发或动画完成而改变。

但动画仅在第一次有效。

为了简化这一点,我只是让一个矩形在 Canvas 中从 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;
}

最佳答案

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

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

关于c# - 我的 wpf 动画代码有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37386422/

相关文章:

c# - 一个数据库上的多个 DbContext 代码优先迁移

c# - VoIP/SIP 软电话 C# WPF

c# - 为什么两个多重绑定(bind)中只有一个有效?

c# - 如何绕过应用程序范围设置为只读?

html - SVG 动画仅在页面完全加载后开始。是真的吗?

c# - 如何从 C# List<string> 中删除空行?

c# - 我如何告诉 Resharper 我的 IEnumerable 方法删除了空值?

c# - 事件触发触发两次

java - 如何让线条动画更流畅?

ios - 为 CGAffineTransformMakeRotation Swift 设置旋转点