How to make a wpf countdown timer?

user2419978 picture user2419978 · May 25, 2013 · Viewed 31.6k times · Source

I want to create wpf countdown timer that display the result as hh:mm:ss into textbox, I would be thankful for anyone help.

Answer

kmatyaszek picture kmatyaszek · May 25, 2013

You can use DispatcherTimer class (msdn).

Duration of time you can hold in TimeSpan structure (msdn).

If you want formatting TimeSpan to hh:mm:ss you should invoke ToString method with "c" argument (msdn).

Example:

XAML:

<Window x:Class="CountdownTimer.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBlock Name="tbTime" />
    </Grid>
</Window>

Code-behind:

using System;
using System.Windows;
using System.Windows.Threading;

namespace CountdownTimer
{
    public partial class MainWindow : Window
    {
        DispatcherTimer _timer;
        TimeSpan _time;

        public MainWindow()
        {
            InitializeComponent();

            _time = TimeSpan.FromSeconds(10);

            _timer = new DispatcherTimer(new TimeSpan(0, 0, 1), DispatcherPriority.Normal, delegate
                {
                    tbTime.Text = _time.ToString("c");
                    if (_time == TimeSpan.Zero) _timer.Stop();
                    _time = _time.Add(TimeSpan.FromSeconds(-1));                    
                }, Application.Current.Dispatcher);

            _timer.Start();            
        }
    }
}