Search code examples
c#wpftimercountdown

WPF timer countdown


I am wondering about timers in WPF.

what i basically know is how to make a simple count down timer (label) count down like this code:

private void buttonStartOne_Click(object sender, RoutedEventArgs e)
{
    counterOne = new DispatcherTimer();
    counterOne.Tick += new EventHandler(counterOne_Tick);
    counterOne.Interval = new TimeSpan(0, 0, 1);

    counterOneTime = 10;
    counterOne.Start();
}

private void counterOne_Tick(object sender, EventArgs e)
{
// code goes here

    if (counterOneTime > 0)
    {
        counterOneTime--;
        labelCounterOne.Content = counterOneTime + "s";
    }
    else
        counterOne.Stop();
}

In this example code above, the countdown is just 10 seconds. What i want, and dont know is how i should make it as: HH:mm:ss and than make it count down. Would you do that with 3 separate counters and labels (one for each time unit)? Or what should be a better way to tackle this one?


Solution

  • You could convert your Timespan to a string with the ToString(string format) method. Set the resulting string on your label