You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现DispatcherTimer倒计时功能?附正向计时代码示例

Convert DispatcherTimer to Countdown Logic

Here's the modified version of your code that implements countdown functionality instead of forward counting. I've adjusted the tick handler to decrement time values, handle rollovers properly, and added logic to stop the timer once it reaches zero.

public TestTimer() 
{ 
    Timer = new DispatcherTimer(); 
    Timer.Interval = new TimeSpan(0, 0, 1); 
    Timer.Tick += TimerTick; 
    // Removed auto-start: Set your desired countdown time first before calling StartTimer()
} 

private DispatcherTimer Timer; 

private int _seconds; 
public int Seconds 
{ 
    get { return _seconds; } 
    set { if(value > -1 && value < 61) _seconds = value; } 
} 

private int _minutes; 
public int Minutes 
{ 
    get { return _minutes; } 
    set { if (value > -1 && value < 61) _minutes = value; } 
} 

private int _hours; 
public int Hours 
{ 
    get { return _hours; } 
    set { if (value > -1 && value < 25) _hours = value; } 
} 

public void StartTimer() 
{ 
    // Only start if there's time left to count down
    if (Hours > 0 || Minutes > 0 || Seconds > 0)
        Timer.Start(); 
} 

public void StopTimer() 
{ 
    Timer.Stop(); 
} 

private void TimerTick(object sender, EventArgs e) 
{ 
    // Decrement seconds first
    Seconds--;

    // Handle second rollover (when seconds go below 0)
    if (Seconds < 0)
    {
        Seconds = 59;
        Minutes--;

        // Handle minute rollover
        if (Minutes < 0)
        {
            Minutes = 59;
            Hours--;

            // Handle hour rollover: reset and stop when time runs out
            if (Hours < 0)
            {
                Hours = 0;
                Minutes = 0;
                Seconds = 0;
                StopTimer();
            }
        }
    }

    // Update formatted time string with current countdown value
    TimeFormat = string.Format("{0:00}:{1:00}:{2:00}", Hours, Minutes, Seconds);
}

Key Changes Explained:

  • Tick Handler Rewrite: Replaced increment logic with decrement. When seconds hit -1, we reset to 59 and subtract from minutes, repeating the same rollover logic for minutes to hours.
  • Auto-Stop on Zero: When all time values reach zero, the timer stops automatically to prevent negative time displays.
  • Start Guard: Added a check in StartTimer() to avoid starting the timer if no countdown time is set.
  • Constructor Adjustment: Removed the automatic StartTimer() call so you can set your desired countdown time (e.g., 1 hour, 30 minutes) before starting the timer.

Example Usage:

// Set up a 25-minute countdown
var countdown = new TestTimer();
countdown.Minutes = 25;
countdown.StartTimer();

内容的提问来源于stack exchange,提问作者Amazing User

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:31:41