Get DoubleAnimation Reference Object from BeginAnimation

131 views Asked by At

I want to add a simple double animation with code-behind to apply a fadein to n objects created at runtime:

foreach (var rect in howmanyrect) {

   Rectangle bbox = new Rectangle {
       Width = rect.Width, 
       Height = rect.Height, 
       Stroke = Brushes.BlueViolet,
       Opacity = 0D 
   };

   DoubleAnimation da = new DoubleAnimation {
        From = 0D,
        To = 1D,
        Duration = TimeSpan.FromMilliseconds(500D),
        RepeatBehavior = new RepeatBehavior(1),
        AutoReverse = false
   };

GridContainer.Children.Add(bbox);
Canvas.SetLeft(bbox, rect.Left);
Canvas.SetTop(bbox, rect.Top);

bbox.Tag = da; // <- Look HERE
bbox.BeginAnimation(OpacityProperty, da);

After this, when requested, delete the objects collection with fadeout:

foreach (var child in GridContainer.Children) {

    Rectangle bbox = (Rectangle) child;

    DoubleAnimation da = (DoubleAnimation) bbox.Tag; // <- Look HERE
    da.From = 1D;
    da.To = 0D;

    var childCopy = child; // This copy grants the object reference access for removing inside a forech statement
    da.Completed += (obj, arg) => viewerGrid.Children.Remove((UIElement) childCopy);

    bbox.BeginAnimation(OpacityProperty, da);

}

This code works perfectly but it's a workaround. In my first revision I created a new Doubleanimation object in the delete method but when I started the animation every object excetutes the first and the second animation before being deleted. So I decide to pass a reference to the DoubleAnimation instance with the Tag property and change the animation properties.

Is there another way to obtain a reference to the DoubleAnimation object attached with BeginAnimation or to avoid the first animation to be repeated?

Thanks Lox

0

There are 0 answers