Export (0) Print
Expand All

How to: Create a Timer

Silverlight

To create a timer in Silverlight, use the DispatcherTimer class in the System.Windows.Threading namespace.

The following example shows a simple counter that uses a DispatcherTimer.

Run this sample.

<Grid x:Name="LayoutRoot" Background="White">

  <!-- Just a TextBlock to show the output of the timer. -->
  <TextBlock Loaded="StartTimer" x:Name="myTextBlock" />
</Grid>
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;

// Raised every 100 miliseconds while the DispatcherTimer is active.
public void Each_Tick(object o, EventArgs sender)
{
    myTextBlock.Text = "Count up: " + i++.ToString();
}

Community Additions

ADD
Show:
© 2014 Microsoft