C# WPF添加timer,实现Timer事件

C# WPF添加timer  


在 WPF 中不再有类似 WinForm 中的 Timer 控件,因此,需要使用 DispatcherTimer 类来实现类似 Timer 的定时执行事件,该事件使用委托方式实现。DispatcherTimer 类在 System.Windows.Threading 下,需要 using System.Windows.Threading 命名空间。


在WPF中不能直接添加timer控件,只能手动自己添加


namespace CountDown
{   
  public partial classMainWin : Window
    {
       private DispatcherTimer timer;
	//设置定时器          
	timer = new DispatcherTimer();
       timer.Interval = new TimeSpan(10000000);   //时间间隔为一秒
       timer.Tick += new EventHandler(timer_Tick);
 	//转换成秒数
       Int32 hour= Convert.ToInt32(HourArea.Text);
       Int32 minute = Convert.ToInt32(MinuteArea.Text);
       Int32 second = Convert.ToInt32(SecondArea.Text);           
      //开启定时器          
      timer.Start();
}
  private void timer_Tick(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }

简单示例代码如下,该代码实现在 WPF 窗体的标题实时显示当前系统时间。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace TimerWindow
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        DispatcherTimer timer = new DispatcherTimer();

        public MainWindow()
        {
            InitializeComponent();

            timer.Tick += new EventHandler(timer_Tick);
            //timer.Interval = TimeSpan.FromSeconds(0.1);   //设置刷新的间隔时间
            timer.Start();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            this.Title = string.Concat("TimerWindow  ", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
        }

    }
}




         使用TimeSpan类(System.TimeSpan)
      TimeSpan对象表示时间间隔或持续时间,按正负天数、小时数、分钟数、秒数以及秒的小数部分进行度量。用于度量持续时间的最大时间单位是天。更大的时间单位(如月和年)的天数不同,因此为保持一致性,时间间隔以天为单位来度量。


      TimeSpan 对象的值是等于所表示时间间隔的刻度数。一个刻度等于 100 纳秒,TimeSpan 对象的值的范围在 MinValue 和 MaxValue 之间。


      TimeSpan 值可以表示为 [-]d.hh:mm:ss.ff,其中减号是可选的,它指示负时间间隔,d分量表示天,hh 表示小时(24 小时制),mm 表示分钟,ss 表示秒,而 ff为秒的小数部分。即,时间间隔包括整的正负天数、天数和剩余的不足一天的时长,或者只包含不足一天的时长。例如,初始化为 1.0e+13 刻度的 TimeSpan 对象的文本表示“11.13:46:40”,即 11 天,13 小时,46 分钟和 40  秒。






发布了14 篇原创文章 · 获赞 10 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_36545099/article/details/77973213
今日推荐