Silverlight 3: Using a Timer
While working on a Silverlight 3 website, I found I had a need for a Timer. After looking through the 60+ controls that are part of the Silverlight Toolkit, I realized there wasn’t one there. Fortunately, I didn’t have to get discouraged, because there is a nice timer that can be accessed and used in the System.Windows.Threading namespace, called the “DispatcherTimer”.
You can use the timer in a Silverlight UserControl by declaring it at the member level, at the top of your class as follows. Use the “WithEvents” keyword to enable it’s selection from the Class Name dropdown list:
Partial Public Class MyUserControl
Inherits UserControl
'Declare the timer at the member level using
' the WithEvents keyword
Private WithEvents mTimer As _
New System.Windows.Threading.DispatcherTimer()
Public Sub New()
InitializeComponent()
End Sub
End Class
After declaring the timer, select if from the Class Name dropdown list at the top of the code window, and then select the “Tick” method from the Method Name dropdown list, as follows:
When you select the “Tick” method from the Method Name dropdown list, the mTimer_Tick event will be automatically created. This is the event that gets fired at the specified intervals:
Private Sub mTimer_Tick( _
ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles mTimer.Tick
'Insert the code here that will be executed
' at the specified interval.
End Sub
The final thing to do is set the timer’s Interval, and then call the Start method. This can be perform in whatever method you prefer, I will use the constructor:
Public Sub New()
InitializeComponent()
'Initialize timer for 5 seconds
mTimer.Interval = New TimeSpan(0, 0, 5)
'Start the timer
mTimer.Start()
End Sub
The complete class looks like the following:
Partial Public Class MyUserControl
Inherits UserControl
'Declare the timer at the member level using
' the WithEvents keyword
Private WithEvents mTimer As _
New System.Windows.Threading.DispatcherTimer()
Public Sub New()
InitializeComponent()
'Initialize timer for 5 seconds
mTimer.Interval = New TimeSpan(0, 0, 5)
'Start the timer
mTimer.Start()
End Sub
Private Sub mTimer_Tick( _
ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles mTimer.Tick
'Insert the code here that will be executed
' at the specified interval.
End Sub
End Class
And that’s all there is to it! I used the timer to change the pictures in a Silverlight SlideShow, and it works great! Hopefully you’ll find some creative uses for it as well.
0 comments: