How to Include Blend Simulations into WPF Code Behind

While really a WPF / Blend recipe, it is worth reporting here.

In Blend, you can create a storyboard that includes an animation. The question is, how can you trigger that animation in the C# (code-behind) code?

Here is the code of how you can start any of the storyboards you've created in Blend directly from the C# code. The trick is to use the 'FindResource' method to look up the storyboard, casting it to a valid object, and then call the Begin() method to start the animation.

  • Add the following code to the section in your program where you want to start the storyboard animation.
  • Remember to remove all the 'Triggers' for this storyboard from Blend -- otherwise the Storyboard will be triggered automatically when you load the control (or by any other triggered event that is associated with this storyboard).
try
{
 // Get the storyboard from the resources of the user control.
 // Replace 'myStoryboard' with the name of the storyboard you're looking for.
 // Replace 'userControl' with the user control you've created.
 Storyboard storyboard = (Storyboard)this.userControl.FindResource("myStoryboard");

  // Still check that the storyboard is not equals null
  if (storyboard != null)
  {
       // Start the animation
       storyboard.Begin();
  }
}
catch (ResourceReferenceKeyNotFoundException exception)
  {
  // Storyboard not found
  // Handle the 'exception'
  }