1

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.

Abhi
  • 141
  • 2
  • 4
  • 17
  • 2
    Use [TimeSpan](https://msdn.microsoft.com/en-us/library/bb384267(v=vs.110).aspx) instead. – Jasen Feb 27 '17 at 18:33
  • 1
    See marked duplicate. Include `hh` in addition to the `mm` and `ss` indicated in that answer. – Peter Duniho Feb 27 '17 at 18:42
  • @PeterDuniho: I'm not if it's a duplicate , since adding the "hh:mm:ss" will actually show the current time and increment in seconds. What I wanted was the answer posted by Roma below. – Abhi Feb 27 '17 at 19:09

1 Answers1

2

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();
}
Roman
  • 11,966
  • 10
  • 38
  • 47