开发者

Concept for animating many elements in WPF

I am in the situation to visualize many seperate elements. With many I mean 15 to 40.

It is to cumbe开发者_StackOverflowrsome to animate every element by hand in XAML. The animatiom is straightforward, all elements are decreased in size or moved into one direction. It's a flow-chart which has to be minimized.

Is there a way to animate these elements, maybe in a programmatically way so I can loop over the elements any apply similiar animation?


You can create the animations in code and put them in a Storyboard, so that they run syncronously:

    <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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜