如何使用MVVM从零开始在WPF中显示Timer?

时间:2017-02-27 18:17:11

标签: c#

我想显示一个在"秒内增加的计时器"像这样:

00:00:01

00:00:02

0时00分03秒

我尝试使用调度计时器,但它只显示在秒,如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();
  }

我知道我必须更改DateTime.Now.Second部分,但我不确定需要做什么才能得到它。

P.S:我不确定这实际上是否是一个重复的问题。但我从罗马下面得到了确切的代码。

1 个答案:

答案 0 :(得分:1)

private DispatcherTimer dispatcherTimer = null;之后添加字段:

private int _totalSecond = 0;

并更改Tick处理程序:

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