Transformation
Now that you have your first Silverlight application running, modify it to do some animation so that you can do justice to Silverlight. As an example, let's modify the button so that it can rotate and update the time simultaneously.
Using the same project, add a new Timeline to the XAML file in Expression Blend 2. After adding the new Timeline, your XAML code should look like this:
<Canvas.Triggers>
<EventTrigger RoutedEvent="Canvas.Loaded">
<BeginStoryboard>
<Storyboard x:Name="Timeline1"/>
</BeginStoryboard>
<BeginStoryboard>
<Storyboard x:Name="Timeline2"/>
</BeginStoryboard>
</EventTrigger>
</Canvas.Triggers>
In the
Page.xaml.vb file, declare a private member variable called degrees:
Partial Public Class Page
Inherits Canvas
Private degrees As Integer = 0
In the
Page_Loaded() subroutine, add a new duration for the second Timeline:
Public Sub Page_Loaded(ByVal o As Object, ByVal e As EventArgs)
' Required to initialize variables
InitializeComponent()
'---display the clock---
Me.Timeline1.Duration = New Duration(New TimeSpan(0, 0, 1))
Me.Timeline1.Begin()
'---rotate the clock---
Me.Timeline2.Duration = New Duration(New TimeSpan(100))
Me.Timeline2.Begin()
End Sub
Here, you are setting the
Timeline2's interval to 100 milliseconds (the
TimeSpan object constructor is overloaded). Every 100 milliseconds, the
Completed event of
Timeline2 is fired, and here you call the
PerformTransformation() subroutine:
Private Sub Timeline2_Completed( _
ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles Timeline2.Completed
PerformTransformation()
Me.Timeline2.Begin()
End Sub
This subroutine uses the
RotateTransform object to perform a transformation on an object. Here, you will use it to rotate the button one degree at a time:
Private Sub PerformTransformation()
'---use a RotateTransform object to perform transformation---
Dim rt As New RotateTransform
'---define the transformation---
With rt
.Angle = degrees
.CenterX = 50
.CenterY = 50
End With
'---increment the degree of rotation---
degrees += 1
'---transform the button---
btnTime.RenderTransform = rt
End Sub
In addition, when the user clicks on the button, the button will be reset to its original position and start rotating again:
Private Sub btnTime_MouseLeftButtonDown( _
ByVal sender As Object, _
ByVal e As System.Windows.Input.MouseEventArgs) _
Handles btnTime.MouseLeftButtonDown
degrees = 0
PerformTransformation()
End Sub
Figure 16 shows how the button looks when it's run.