Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
I've seen several questions related to timers on forums and in internal mail so I thought I'd toss up a simple example. To create a timer, you have to use the DispatcherTimer in the System.Windows.Threading namespace.
Here's an example of a simple counter that uses DispatcherTimer: Run this sample.
And below is the code:
<Grid x:Name="LayoutRoot" Background="White">
<!-- Just a TextBlock to show the output of the timer. -->
<TextBlock Loaded="StartTimer" x:Name="myTextBlock" />
</Grid>
// C#
public void StartTimer(object o, RoutedEventArgs sender)
{
System.Windows.Threading.DispatcherTimer myDispatcherTimer = new System.Windows.Threading.DispatcherTimer();
myDispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 100); // 100 Milliseconds
myDispatcherTimer.Tick += new EventHandler(Each_Tick);
myDispatcherTimer.Start();
}
// A variable to count with.
int i = 0;
// Fires every 100 miliseconds while the DispatcherTimer is active.
public void Each_Tick(object o, EventArgs sender)
{
myTextBlock.Text = "Count up: " + i++.ToString();
}
Before Silverlight 2 (with Silverlight 1.0) you could create an animation using a Storyboard, however, Storyboards are for animations so this was a hack. Also, I believe the DispatcherTimer route offers better performance. Still, if you are using Silverlight 1.0 or have some reason for wanting to use a Storyboard to simulate a timer, see How to: Create a Timer in the Silverlight 1.0 documentation.
Sam Landstrom - MSFT
Comments
Anonymous
April 01, 2008
PingBack from http://blogs.msdn.com/silverlight_sdk/archive/2008/03/27/make-a-silverlight-timer-silverlight-2.aspxAnonymous
November 15, 2008
[Silverlight 2] Creare un Timer