Skip to main content
 首页 » 编程设计

c#之WPF 如何轻松地在代码后面链接动画

2024年02月06日12lidabo

我有一个 Canvas :

<Canvas x:Name="testCanvas" Height="40" Width="460" VerticalAlignment="Top"> 
    <Image Source="versus2-top-p1.png"/> 
    <Label x:Name="testLabel" Content="TEST" /> 
</Canvas> 

我正在按如下方式对其进行动画处理:

private void button_Click(object sender, RoutedEventArgs e) 
{ 
    testCanvas.BeginAnimation(Canvas.MarginProperty, 
        new ThicknessAnimation(new Thickness(0, -40, 0, 0), TimeSpan.FromSeconds(1)) 
    ); 
 
    testLabel.Content = "ANIMATION TEST"; 
 
    testCanvas.BeginAnimation(Canvas.MarginProperty, 
        new ThicknessAnimation(new Thickness(0, 0, 0, 0), TimeSpan.FromSeconds(1)) 
    ); 
} 

问题是动画没有链接。所有 3 行代码都同时被触发。我想依次运行这三行代码:

  1. 将上边距移至 -40
  2. 更改 testLabel 中的文本
  3. 将上边距移至 0

最简单的方法是什么?

请您参考如下方法:

想通了...使用 animation.Completed 事件处理程序。

    private void button_Click(object sender, RoutedEventArgs e) 
    { 
        ThicknessAnimation animate = new ThicknessAnimation(new Thickness(0, -40, 0, 0), TimeSpan.FromSeconds(1)); 
        animate.Completed += new EventHandler(animate_Completed); 
 
        testCanvas.BeginAnimation(Canvas.MarginProperty, animate); 
    } 
 
    private void animate_Completed(object sender, EventArgs e) 
    { 
        testLabel.Content = "ANIMATION TEST"; 
 
        testCanvas.BeginAnimation(Canvas.MarginProperty, 
            new ThicknessAnimation(new Thickness(0, 0, 0, 0), TimeSpan.FromSeconds(1)) 
        ); 
    }