WynApse Home Page
Home    Blog    About    Contact       
Latest Article:

My Tags:
My Sponsors:

Lifetime Member:

Silverlight Single Storyboard Test

This is a short example based on a series of forum postings at the Silverlight Forums site:The common theme in these two threads is that someone was trying to run code using a single animation to be used on multiple targets. A great example of this would be to have multiple buttons on a page, each with animated-gradient rollovers, and have only one set of animation code to support all the buttons.

The Problem

The problem was that although it seemed pretty obvious that you need to set the Storyboard.Target, it was only working once. The second use threw an error or two.

The first couple times I read the postings, I thought they were more complex than I wanted to quickly look at, but at some point realized not only was it not that complex, but when I looked at the code, I remembered something we had been doing back in December and January with WPF/E.

The Solution

The solution to this problem is extremely simple. The only thing that has to happen is to explicitly stop the animation. Accepting that the animation is complete by either waiting for the animation to finish running, or even for a Completed script to run isn't enough to get the job done. You have to execute stop() on the storyboard.

That's precisely what I've done in the JavaScript for the examples shown above. The red/blue ellipses cause "MoveIt" to be executed on Left Mouse Up. "MoveIt" sets the Storyboard.TargetName on the "MoveIt" Storyboard, and then calls begin() on that Storyboard.

When "MoveIt" completes, it executes "MoveDone". In "MoveDone", I execute stop() on the Storyboard, and that allows the Targetname to be set again with the next mouse up message.

There's just a little more than that involved, because I set a flag to avoid clicking the second ellipse while the first one is animating. With button rollovers, this handshaking would probably not be necessary because it would happen very fast.

JavaScript for producing this page:

<script type="text/javascript">
var fDone = 1;

function MoveIt(sender, args)
if (fDone == 1)
fDone = 0;
var sWhich = sender.Name.toString();

function MoveDone(sender, args)
fDone = 1;


XAML for producing this page:


<Ellipse x:Name="BlueEllipse" Cursor="Hand"
Height="20" Width="20" Canvas.Left="0" Canvas.Top="10" MouseLeftButtonUp="MoveIt"
Fill="Blue" />

<Ellipse x:Name="RedEllipse" Cursor="Hand"
Height="20" Width="20" Canvas.Left="0" Canvas.Top="50" MouseLeftButtonUp="MoveIt"
Fill="Red" />

<Storyboard x:Name="MoveIt" Completed="MoveDone">
<DoubleAnimation Storyboard.TargetProperty="(Canvas.Left)" From="0" To="280" Duration="0:0:1" />

Copyright © 2006-2022, WynApse