Prevent a Silverlight animation from running twice

By default in Silverlight a user can launch the same animation several times, even if the animation is not finished. Side effects: the animation starts again and your code (if any) runs twice. Sometimes this can be annoying.

Let’s say you have a button that starts a storyboard with animations and runs some code, nothing prevent the user from clicking several times on the button.

Unfortunately there is no “isRunning” property on the Storyboard element, but you can implement a very easy workaround with the help of the Completed event and a boolean variable :

public partial class Page : UserControl
    bool isPlaying = false;

    public Page()
        // Required to initialize variables

        Storyboard1.Completed += new EventHandler(Storyboard1_Completed);

    void Storyboard1_Completed(object sender, EventArgs e)
        isPlaying = false;

    private void btn_Click(object sender, RoutedEventArgs e)
       if (!isPlaying)
           isPlaying = true;
// more code here; } } }

Note: for a simple example like this you could also disable the button while the animation is running.




Technorati Tags: