c# - 在计时器倒计时中包括小时

标签 c# wpf timespan dispatchertimer

我正在尝试创建一个包括小时数的倒计时。

private int time = 3660;        

public MainWindow()
{
    var vm = new TimerViewModel();

    InitializeComponent();

    // get display setting - 2 means extended
    int displayType = Screen.AllScreens.Length;

    // set the windows datacontext
    DataContext = vm;

    // set up the timedispatcher
    dt.Interval = new TimeSpan(0, 0, 1);
    dt.Tick += Timer_Tick;
}   

private void Timer_Tick(object sender, EventArgs e)
{
    switch(time)
    {
        case int x when x > 10 && x <= 20:                 
            TimerPreview.Foreground = Brushes.Orange;

            time--;
            break;

        .....................

        default:
            TimerPreview.Foreground = Brushes.LimeGreen;
            time--;
            break;
    }

    TimerPreview.Content = string.Format("00:{0:00}:{1:00}",  time / 60, time % 60);
}

我无法弄清楚如何让倒计时与小时数一起正常工作。它适用于分钟和秒。

TimerPreview.Content = string.Format("{0:00}:{1:00}:{2:00}", time ???, time ??? 60, time % 60);

我尝试了多种组合,但未能找到解决方案。我错过了什么?非常感谢。

最佳答案

使用 3600(一小时中的秒数),并在分钟上使用模数运算符,就像您在秒上所做的那样(因为您希望 60 分钟看起来滚动进入一个新的小时):

TimerPreview.Content =
    string.Format("{0:00}:{1:00}:{2:00}", time / 3600, (time / 60) % 60, time % 60);

//  320 -> 00:05:20
// 7199 -> 01:59:59
// 7201 -> 02:00:01

关于c# - 在计时器倒计时中包括小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53013247/

相关文章:

C# 比较一天中两个时间的最佳方法

c# - TimeSpan.Parse 天元素范围从 0 到 10675199。为什么是这个数字?

c# - C# 中的任何泛型(参见代码)

c# - 微软对ReaderWriterLockSlim.IsReadLockHeld/IsWriteLockHeld的评论及其后果

c# - 如何从 View 模型中弹出子窗口

c# - 设置属性时PropertyChangedEventHandler为null

c# - WPF 中的圆角文本框

c# - 数学公式在 C# 中的答案与在 Excel 或计算器中的答案不同

c# - Word 编辑器查找模式

php - Timespan - 检查 mysql 中的工作日和一天中的时间