With Silverlight, you animate object's by changing one or more properties over time. In Silverlight, storyboards are used to house animations. Silverlight animations are structured to take place in response to an event (a trigger). There is only one trigger that is supported by Silverlight and that is the EventTrigger. There are 3 types of animations: double, point, and color. In this post, I am going to show you how to create a double animation programmatically. We are going to make a duck fly!
First, I am going to create my canvas with my duck hunt background. Within my canvas, I have a button and my duck. My plan is to animate my duck across the screen when I click my "Fly!" button.
<ImageBrush ImageSource="Images/canvas.png" />
<local:Duck x:Name="Duck1" Canvas.Left="26" Canvas.Top="57" />
<Button x:Name="btnFly" Height="30" Width="100" Content="Fly!" Background="#FF000000"/>
As I mentioned in the intro, I described how a Storyboard houses 1-to-many animations. Each animation may vary in type and may also target different objects and associated object properties. In our example, we want to animate the Canvas.Left position of our duck from the left area of the canvas to the right when the "Fly!" button is clicked. To accomplish this, we are going to use a DoubleAnimation. We can accomplish this in XAML or programmatically. I see lots of examples on the web for using XAML so I'll do this programmatically.
Private Sub btnFly_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnFly.Click
Dim dur As Duration = New Duration(TimeSpan.FromSeconds(3))
Dim da As DoubleAnimation = New DoubleAnimation()
.From = 26
.To = 425
.Duration = dur
Dim sb As Storyboard = New Storyboard()
sb.Duration = dur
Storyboard.SetTargetProperty(da, New PropertyPath("(Canvas.Left)"))
I first create the duration object and set it to span 3 seconds. I define the double animation to begin at 26 and go to 425 and assign it my 3 second duration. I then create my storyboard and add my animation to it. I associate my animation to my duck object and tell the animation to update the duck's Canvas.Left property (26 to 425 over 3 seconds). When all is wired up, I then call the storyboard's Begin() method to start the animation. That's it! You could also add an event to fire when the animations are complete for the storyboard via the Complete event.
Animation_Programmatic_Soln.zip (2.12 mb)