Timer In WPF

This article demonstrates how to implement timer in WPF using the DispatchTimer class.

In this article and the attached project, I am going to create a WPF application that has a ListBox control and this control is being updated every second with current time. The application looks like Figure 1.

WPF Timer Application
Figure 1

Creating a DispatchTimer

XAML does not support any timer feature and WPF does not have a Timer control or class. The DispatchTimer class defined in the System.Windows.Threading namespace is used to add timer functionality in WPF.

The following code snippet creates a DispatchTimer object.

  1. DispatcherTimer dispatcherTimer = newDispatcherTimer();   

Setting Tick and Interval

The Tick event handler executes when a DispatchTimer is started on a given Interval. The following code snippet sets the Tick and Interval of a DispatchTimer.

  1. dispatcherTimer.Tick += newEventHandler(dispatcherTimer_Tick);  
  2. dispatcherTimer.Interval = newTimeSpan(0, 0, 1);  

Start DispatchTimer

The Start method is used to start a DispatchTimer.

  1. dispatcherTimer.Start();  

Complete Code Example

The code snippet in Listing 1 creates a DispatchTimer, sets its Tick event and Interval property and calls its Start method. The Start method starts the timer and the Tick event handler is executed on the given Interval value. In this code, on the Tick event handler, I update a ListBox control and add the current time. I also set the selected item of the ListBox to the currently added item and make sure this item is visible in the ListView. 

  1. privatevoid Window_Loaded(object sender, RoutedEventArgs e) {  
  2.     DispatcherTimer dispatcherTimer = newDispatcherTimer();  
  3.     dispatcherTimer.Tick += newEventHandler(dispatcherTimer_Tick);  
  4.     dispatcherTimer.Interval = newTimeSpan(0, 0, 1);  
  5.     dispatcherTimer.Start();  
  6. }  
  7. privatevoid dispatcherTimer_Tick(object sender, EventArgs e) {  
  8.     listBox1.Items.Add(DateTime.Now.ToString("HH:mm:ss"));  
  9.     CommandManager.InvalidateRequerySuggested();  
  10.     listBox1.Items.MoveCurrentToLast();  
  11.     listBox1.SelectedItem = listBox1.Items.CurrentItem;  
  12.     listBox1.ScrollIntoView(listBox1.Items.CurrentItem);  
  13. }  

Listing 1

Summary

In this article, I discussed how we can create a DispatchTimer control to build timer applications in WPF and C#. We saw how to update a ListBox control every second with the current time.


Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.