【问题标题】:C# DispatchTimer WPF Countdown TimerC# DispatcherTimer WPF 倒数计时器
【发布时间】:2021-10-08 12:42:17
【问题描述】:

我有一个包含倒数计时器的 WPF 应用程序,我被它的格式化部分所困扰,我几乎没有编程经验,这是我第一次使用 c#。我想使用 DispatchTimer 从 15 分钟 开始倒计时,但到目前为止,我的计时器只从 15 秒 开始倒计时>,有什么想法吗?

到目前为止我的倒计时:

 public partial class MainWindow : Window
    {
        private int time = 15;
     

        private DispatcherTimer Timer;
        public MainWindow()
        {
            InitializeComponent();
            Timer = new DispatcherTimer();
            Timer.Interval = new TimeSpan(0,0,1);
            Timer.Tick += Timer_Tick;
            Timer.Start();
        }

        void Timer_Tick(object sender, EventArgs e) {
            if (time > 0)
            {
                time--;
                TBCountDown.Text = string.Format("{0}:{1}", time / 60, time % 60);
                
            }
            else {
                Timer.Stop();
            }
        }

输出如下:

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    更好的方法是使用 TimeSpan 而不是带有数字的 int。在以下应用程序中设置 TimeSpan 值将按我的意愿进行倒计时。

    TimeSpan.FromMinutes 几分钟

    TimSpan.FromSeconds 几秒钟

    您可以查看here了解更多详细信息。

    public partial class MainWindow : Window
    {
        DispatcherTimer dispatcherTimer;
        TimeSpan time;
        public MainWindow()
        {
            InitializeComponent();
    
            time = TimeSpan.FromMinutes(15);
            dispatcherTimer = new DispatcherTimer();
            dispatcherTimer.Interval = TimeSpan.FromSeconds(1);
            dispatcherTimer.Tick += DispatcherTimer_Tick;
            dispatcherTimer.Start();
        }
    
        private void DispatcherTimer_Tick(object sender, EventArgs e)
        {
            if (time == TimeSpan.Zero) dispatcherTimer.Stop();
            else
            { 
                time = time.Add(TimeSpan.FromSeconds(-1));
                MyTime.Text = time.ToString("c");
            }
        }
    }
    

    Xaml 代码

       <Grid>
        <TextBlock Name="MyTime" />
    </Grid>
    

    【讨论】:

      【解决方案2】:

      您以 1 秒的间隔初始化 DispatchTimer:Timer.Interval = new TimeSpan(0,0,1); 并且每次 TimerTick 都会减少您的 timefield。

      所以,time应该从您想要倒计时的总秒数开始。如果您从 15 开始,您的倒数计时器将从 15 秒倒数到零。 如果要倒计时 15 分钟,则必须将 time 初始化为 900 (15 x 60'')。

      【讨论】:

      • 感谢您的帮助,这可行,但我希望获得如下格式:15:00
      猜你喜欢
      • 1970-01-01
      • 2015-02-18
      • 1970-01-01
      • 2015-05-05
      • 1970-01-01
      • 2011-12-19
      • 1970-01-01
      • 1970-01-01
      • 2021-02-24
      相关资源
      最近更新 更多