Discorax's House of w00t

A collection of technology lessons learned though doing. Sharing of code samples, tips and tricks for web design and development. Written by an interactive designer/developer for other designer/developers.


Access WPF Storyboard in XAML from code-behind (C#)

At more than one time working with WPF I've wanted to create a generic Storyboard using Blend because it saves me time and gives me a nice time line type layout to create/tweak my Storyboard. What happens is when you save the Storyboard it's added to the Windows.Resources collection the XAML. In Silverlight you can access these Storyboard resources directly using their x:Name value. In WPF, however, you need to do it slightly differently.

  • First, You need to specify x:Key for each Storyboard

  • Storyboards must be found using TryFindResource:

    Storyboard myStoryboard = (Storyboard)TryFindResource("myStoryboard");

  • TryFindResource will only work if the Storyboard is in the Window.Resources section of the XAML and you're in the code-behind of that XAML

  • Once you have the reference to the Storyboard contained in a variable you can call the various Storyboard methods on it. To run it, use the Begin method:


Here is a quick code snippet to help you out.

Here is the XAML:

Labels: , ,


Anonymous Anonymous said...

Thanks, helped me a lot. :)

3:10 AM  
Anonymous Anonymous said...

Thanks from me to.

My "Pro WPF inc# 2008" book says you only need to set the
Storyboard Name ="" but I found only your solution worked.

4:55 AM  

Post a Comment

Links to this post:

Create a Link

<< Home