WPF Timer替代者

做过WinForm开发的都会郁闷WPF竟然没有Timer。

今天想在WPF中用Timer可是发现WPF没有Timer类,找了半天发现新增了一个 DispatcherTimer确实好用和WinForm中Timer用法相似。

-----------------------------------------------------------------------------------------------------------------------------

引:银光中国

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

创建了名为 dispatcherTimerDispatcherTimer 对象。 事件处理程序 dispatcherTimer_Tick 被添加到 dispatcherTimerTick 事件中。 使用 TimeSpan 对象将 Interval 设置为 1 秒,并启动了计时器。

1 // DispatcherTimer setup
2  dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
3 dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
4 dispatcherTimer.Interval = new TimeSpan(0,0,1);
5 dispatcherTimer.Start();

Tick 事件处理程序将更新显示当前秒数的 Label,并且它将对 CommandManager 调用 InvalidateRequerySuggested

 

1 // System.Windows.Threading.DispatcherTimer.Tick handler
2  //
3  // Updates the current seconds display and calls
4  // InvalidateRequerySuggested on the CommandManager to force
5  // the Command to raise the CanExecuteChanged event.
6  private void dispatcherTimer_Tick(object sender, EventArgs e)
7 {
8 // Updating the Label which displays the current second
9   lblSeconds.Content = DateTime.Now.Second;
10
11 // Forcing the CommandManager to raise the RequerySuggested event
12 CommandManager.InvalidateRequerySuggested();
13 }
posted @ 2011-03-18 12:00  .net万剑  阅读(6905)  评论(0编辑  收藏  举报