Timer in WPF
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.
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.
DispatcherTimer dispatcherTimer = new DispatcherTimer();
Start DispatchTimer
The Start method is used to start a DispatchTimer.
dispatcherTimer.Start();
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(); }
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.
Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.