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 秒。