2015-03-02 139 views
1

我已经建立了一个WPF倒数计时器教程这里以下内容:Simple COUNTDOWN With C# - WPF定时器倒计时时间格式

这里是我使用的代码片段:

void Timer_Tick(object sender, EventArgs e) 
    { 
     if (time > 0) 
     { 
     if (time <= 60) 
     { 
      RebootCountdownWindowTimerText.Foreground = Brushes.Red;   
      time--; 
      RebootCountdownWindowTimerText.Text 
           = string.Format("00:0{0}:{1}", time/60, time % 60); 
     } 
     time--; 
     RebootCountdownWindowTimerText.Text 
           = string.Format("00:0{0}:{1}", time/60, time % 60); 
     } 
     else 
     { 
      Timer.Stop(); 
      serviceController.RebootComputer(); 
     } 
    } 

问题是,当在倒计时进入更低的秒数,格式会改变。例如,从1分钟12秒倒计时:

00:01:12 
00:01:11 
00:01:10 
00:01:9 
00:01:8 
etc... 

我怎样才能重新因子代码,以便它倒计时时,在“十位”的地方适当地显示为0?

+0

除了回答,不依靠定时器被称为 - 完全 - 每1秒。换句话说,不要'时间 - ',计算与上次的差异。另外,当定时器在60以下时,你减去两个单位...所以如果定时器间隔为1秒,则最后一分钟将在30秒内发生:-) – Jcl 2015-03-02 19:30:19

回答

2

使用的数字格式D#,其中#确定的位数等等例如

var time =112; 
Console.WriteLine(string.Format("00:{0:D2}:{1:D2}", time/60, time % 60)); 

会给

00:01:52 
+0

稍微整齐(在我看来)将是'Console.WriteLine (string.Format(“00:{0:D2}:{1:D2}”,(time/60),(time%60)));' - 这是将格式说明符放在格式字符串中, 'ToString'。 – Chris 2015-03-02 19:14:10

+0

这是正确的克里斯将更新 – TYY 2015-03-02 19:27:44

+0

完美!我不知道那个字符串格式约定。很优雅的解决方案 – user3342256 2015-03-02 19:52:06