Abhi Abhi -4 years ago 143
C# Question

How to display a Timer in WPF using MVVM starting at zero?

I want to display a timer that increases in "seconds" like this:

00:00:01

00:00:02

00:00:03

I tried using the dispatch timer but it only displays in Seconds like 01, 02, 03

private DispatcherTimer dispatcherTimer = null;

public string TimerText
{
get
{
return this.timerText;
}
set
{
this.timerText = value;
OnPropertyChanged("TimerText");
}
}

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)
{
TimerText = DateTime.Now.Second.ToString();
CommandManager.InvalidateRequerySuggested();
}


I know I have to change the DateTime.Now.Second part, but I'm not sure what needs to be done to get it like I want.

P.S: I'm not sure if this is actually a duplicate question. But I got the exact code from Roma below.

Answer Source

Add field after private DispatcherTimer dispatcherTimer = null;:

private int _totalSecond = 0;

and change Tick handler:

private void dispatcherTimer_Tick(object sender, EventArgs e)
{
    this._totalSeconds += 1;
    TimerText = string.Format("{0:hh\\:mm\\:ss}", TimeSpan.FromSeconds(this._totalSeconds).Duration());
    CommandManager.InvalidateRequerySuggested();
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download