You are currently viewing Working with the Timer in WPF
Working with the timer WPF

Working with the Timer in WPF

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.

Creating a DispatchTimer

The following code snippet creates a DispatchTimer object.

DispatcherTimer dispatcherTimer = new DispatcherTimer();

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.

dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 1);

Start DispatchTimer

The Start method is used to start a DispatchTimer.

dispatcherTimer.Start();

Complete Code Example

Following code display the digital clock in the Label control. You can use Dispatcher Timer Tick event like a Timer Control in window form Application.

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    DispatcherTimer dispatcherTimer = new DispatcherTimer();
    dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
    dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
    dispatcherTimer.Start();
} 
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
    Label1.Text = DateTime.Now.ToString("HH:mm:ss");   
}