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

Working with the Timer in WPF

1
(1)

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");   
}

 

How useful was this post?

Click on a star to rate it!

Average rating 1 / 5. Vote count: 1

No votes so far! Be the first to rate this post.

As you found this post useful...

Share this post on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?