我在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 :(得分:3)
使用数字格式D#
,其中#
确定位数,例如
var time =112;
Console.WriteLine(string.Format("00:{0:D2}:{1:D2}", time / 60, time % 60));
将给出
00:01:52