在WPF中动画许多元素的概念

时间:2011-03-23 09:04:27

标签: c# .net wpf

我处于可视化许多单独元素的情况中。很多我的意思是15到40岁。

在XAML中手动设置每个元素的动画非常麻烦。动画很简单,所有元素的大小都会减小或移动到一个方向。这是一个必须最小化的流程图。

有没有办法动画这些元素,可能是以编程方式,所以我可以循环元素任何应用类似的动画?

1 个答案:

答案 0 :(得分:0)

您可以在代码中创建动画并将它们放在故事板中,以便它们同步运行:

    <Canvas Name="canvas" Width="200" Height="200">
      <Rectangle Canvas.Left="10" Canvas.Top="20" Stroke="Red" Fill="Orange" Width="30" Height="20" />
      <Ellipse Canvas.Left="50" Canvas.Top="40" Stroke="Blue" Fill="Green" Width="40" Height="30" />
    </Canvas>
    <Button VerticalAlignment="Bottom" Content="Click" Click="Button_Click" />



private void Button_Click(object sender, RoutedEventArgs e)
{
  Storyboard sb = new Storyboard();

  Duration dur = new Duration(TimeSpan.FromSeconds(0.5));

  foreach (FrameworkElement child in canvas.Children) 
  {
    DoubleAnimation leftAnim = new DoubleAnimation(Canvas.GetLeft(child) / 2, dur);
    DoubleAnimation topAnim = new DoubleAnimation(Canvas.GetTop(child) / 2, dur);
    DoubleAnimation widthAnim = new DoubleAnimation(child.Width / 2, dur);
    DoubleAnimation heightAnim = new DoubleAnimation(child.Height / 2, dur);

    sb.Children.Add(leftAnim);
    sb.Children.Add(topAnim);
    sb.Children.Add(widthAnim);
    sb.Children.Add(heightAnim);

    Storyboard.SetTarget(leftAnim, child);
    Storyboard.SetTarget(topAnim, child);
    Storyboard.SetTarget(widthAnim, child);
    Storyboard.SetTarget(heightAnim, child);

    Storyboard.SetTargetProperty(leftAnim, new PropertyPath("(Canvas.Left)"));
    Storyboard.SetTargetProperty(topAnim, new PropertyPath("(Canvas.Top)"));
    Storyboard.SetTargetProperty(widthAnim, new PropertyPath("Width"));
    Storyboard.SetTargetProperty(heightAnim, new PropertyPath("Height"));
  }

  sb.Begin();
}