Make the program wait for animations in a foreach loop

336 Views Asked by At

So what I have is a canvas with various images. What I need is to trigger a animation for one such image in a foreach loop. The problem is the program only runs the last animation of the loop. Is there a way to make the foreach loop pause while the animation is still running, or at least stop the foreach from going to the next loop until it's over. Preferably I'd prefer doing it mostly in code rather than xaml. Here's my canvas xmal code -

    <Canvas Name="AnimationCanvas" HorizontalAlignment="Left" VerticalAlignment="Top" Height="154" Width="292">
        <Image x:Name="img_ShipAttack" Panel.ZIndex="100" Height="91" Canvas.Left="25" Canvas.Top="28" Width="93" RenderTransformOrigin="0,0"/>
        <Image x:Name="img_ShipTarget"  Canvas.Top="28" Panel.ZIndex="100" RenderTransformOrigin="0.5,0.5" Width="93" Canvas.Left="173" Height="93"/>
        <Image x:Name="img_AttackBack" Height="472" Width="651" Panel.ZIndex="0" Canvas.Top="-82" Canvas.Left="-81"/>
        <Image x:Name="img_Pojectile" Panel.ZIndex="90" Height="153" Canvas.Left="-7" Canvas.Top="-3" Width="157" RenderTransformOrigin="0,0"/>
    </Canvas>

and here's my animation method -

    public void Fire(Image target, double seconds)
    {
        var top = Canvas.GetTop(target);
        var left = Canvas.GetLeft(target);
        TranslateTransform trans = new TranslateTransform();
        target.RenderTransform = trans;
        DoubleAnimation anim = new DoubleAnimation(0, 140, TimeSpan.FromSeconds(seconds));

        anim.Completed += new EventHandler(CompletedAnimate);
        trans.BeginAnimation(TranslateTransform.XProperty, anim);
    }

and finally, the troublesome loop -

foreach(var weapon in weapons)
{
              try
                {
                    string weapons = "\\" + weapon.Name + ".png";
                    img_Pojectile.Source = new BitmapImage(new Uri(Directory.GetCurrentDirectory() + "\\Images" + weapons));
                }
                catch
                {
                    try
                    {
                        string weapons = "\\" + weapon.Type + ".png";
                        img_Pojectile.Source = new BitmapImage(new Uri(Directory.GetCurrentDirectory() + "\\Images" + weapons));
                    }
                    catch
                    {
                        img_Pojectile.Source = new BitmapImage(new Uri(Directory.GetCurrentDirectory() + "\\Images\\Default.png"));
                    }
                }

                Fire(img_Pojectile, 1.5);
}

as you might be able to see, I have a Completed event handler in the animation, the problem is that it never trips no matter what. My CompletedAnimation method just sets a bool to true in at the moment.

0

There are 0 best solutions below