Over a million developers have joined DZone.

Creating reusable animations programmatically in Silverlight and Windows Phone

DZone's Guide to

Creating reusable animations programmatically in Silverlight and Windows Phone

· Mobile Zone
Free Resource

As many of you know, I answer a lot of emails regarding Windows Phone development and last week I was asked to show how to create reusable Storyboards with animations programmatically in Silverlight (Windows Phone). Of course, there are plenty tutorials in the internet, but I have decided to create my own. In a nutshell, in this post I am going to create a reusable Storyboard based on DoubleAnimation (for translate transformation), which can be applied for any instance of UIElement.

First of all, I will create a default page, add a Rectangle control to ContentPanel (Grid) and apply a new instance of TranslateTransform to rectangle’s RenderTransform property. If you are familiar with Silverlight, then you, probably, know that Rectangle control inherit from UIElement.

Rectangle rect = new Rectangle
        Fill = new SolidColorBrush(Colors.Green),
        RenderTransform = new TranslateTransform()

Next step is to create a method to produce a reusable Storyboard. This method will take UIElement as parameter and return a new instance of Storyboard. Notice that within the storyboard I have modified TranslateTransform.Y property of UIElement using PropertyPath.

public Storyboard CreateAndApplyStoryboard(UIElement targetElement)
    Storyboard sb = new Storyboard();
    DoubleAnimation animation =
        new DoubleAnimation {From = 0, To = 700};
    Storyboard.SetTarget(animation, targetElement);
        new PropertyPath("(UIElement.RenderTransform).(TranslateTransform.Y)"));
    return sb;

Finally, to try that Storyboard in action, simply, call Begin method for a storyboard instance. Check my code bellow:

Storyboard sb = CreateAndApplyStoryboard(rect);

Now you can create a new instance of such storyboard for every instance that derives from UIElement class.


Published at DZone with permission of Jevgeni Tšaikin. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}