在 WPF 中再也不有相似 WinForm 中的 Timer 控件,所以,須要使用 DispatcherTimer 類來實現相似 Timer 的定時執行事件,該事件使用委託方式實現。DispatcherTimer 類在System.Windows.Threading 下,須要 using System.Windows.Threading 命名空間。 c#
簡單示例代碼以下,該代碼實如今 WPF 窗體的標題實時顯示當前系統時間。 this
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")); } } }