In my last WPF project, I need to update a control with respect to time. In this application I want to display recent update but as we know there is no timer control in WPF. So, I tried to implement timer in WPF by using the DispatchTimer class.
Here, I am going to create a WPF application that has a Items control like Combobox , Listbox etc. In this case I am trying with Combobox control. This control is being updated every second with current time. First of all we create instance of DispatcherTimer class as
DispatcherTimer dispatcherTimer = new DispatcherTimer();
To use DispatcherTimer class you have to include System.Windows.Threading namespace in your application.
Whenever DispatcherTimer is started we have to handled its Tick and Interval events as in the following code snippet
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
//you can set here interval as you want,in this case interval is set every 5 seconds
dispatcherTimer.Interval = new TimeSpan(0, 0, 5);
Then call the start method to start DispatcherTimer as
dispatcherTimer.Start();
//Note: add all above said code during load time.
Then on the Tick event handler update a control (ComboBox in this case) and add the current time. Set the selected item of the ComboBox to the currently added item and make sure this item is visible on Item View.
ComboBox1.Items.Add(DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Second.ToString());
CommandManager.InvalidateRequerySuggested();
ComboBox1.Items.MoveCurrentToLast();
ComboBox1.SelectedItem = ComboBox1.Items.CurrentItem;
ComboBox1.ScrollIntoView(ComboBox1.Items.CurrentItem);
Ok can i use this timer to raise event.
ReplyDeleteActually ,DispatcherTimer is a timer that is integrated into the Dispatcher queue which is processed at a specified interval of time and at a specified priority.
ReplyDeleteIn order to access objects on the user interface (UI) thread, it is necessary to post the operation onto the Dispatcher of the user interface (UI) thread using Invoke or BeginInvoke. Reasons for using a DispatcherTimer opposed to a Timer are that the DispatcherTimer runs on the same thread as the Dispatcher and a DispatcherPriority can be set.
You can use following line of code to accomplish the task :
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(100);
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
Remember that you can only attach event handlers to DispatcherTimer before it's started