Timer in WPF

Creating a DispatchTimer
XAML does not support any timer feature and WPF does not have a Timer control or class. The DispatchTimer class defined in the System.Windows.Threading namespace is used to add timer functionality in WPF.

The following code snippet creates a DispatchTimer object.
DispatcherTimer dispatcherTimer = new DispatcherTimer();

Setting Tick and Interval
The Tick event handler executes when a DispatchTimer is started on a given Interval. The following code snippet sets the Tick and Interval of a DispatchTimer.
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
    dispatcherTimer.Interval = new TimeSpan(0, 0, 1);

Start DispatchTimer
The Start method is used to start a DispatchTimer.
dispatcherTimer.Start();

Complete Code Example
private void Window_Loaded(object sender, RoutedEventArgs e)
{
      DispatcherTimer dispatcherTimer = new DispatcherTimer();
      dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
      dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
      dispatcherTimer.Start();
      TodayDayTop.Text = DateTime.Now.DayOfWeek.ToString();
} 
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
      NowTime.Text = DateTime.Now.ToString("hh:mm:ss tt");
      CommandManager.InvalidateRequerySuggested();
}

Timer in WPF Timer in WPF Reviewed by Unknown on 8:48 AM Rating: 5