Defining a Tick event handler for DispatcherTimer in a Windows 8 application

I am developing an application in Windows 8 Visual studio 11, and I want to define an event handler for the DispatcherTimer instance, as shown below:

public sealed partial class BlankPage : Page { int timecounter = 10; DispatcherTimer timer = new DispatcherTimer(); public BlankPage() { this.InitializeComponent(); timer.Tick += new EventHandler(HandleTick); } private void HandleTick(object s,EventArgs e) { timecounter--; if (timecounter ==0) { //disable all buttons here } } ..... } 

But I get the following error:

 Cannot implicitly convert type 'System.EventHandler' to 'System.EventHandler<object>' 

I am a novice developer to invest 8 applications.

Could you help me?

+7
source share
3 answers

it was almost there :) You don’t need to instantiate a new event handler object, you just need to specify the method that processes the event. Therefore, an event handler.

  int timecounter = 10; DispatcherTimer timer = new DispatcherTimer(); public BlankPage() { this.InitializeComponent(); timer.Tick += timer_Tick; } protected void timer_Tick(object sender, object e) { timecounter--; if (timecounter == 0) { //disable all buttons here } } 

Try reading delegates to understand events Understanding events and event handlers in C #

+8
source

Your code expects HandleTick to have two Object parameters. Not an object parameter or an EventArg parameter.

 private void HandleTick(object s, object e) 

NOT

 private void HandleTick(object s,EventArgs e) 

This is a change that has occurred for Windows 8.

+3
source

WinRT uses Generics more than the standard .NET Runtime. DispatcherTimer.Tick as defined in WinRT, is here :

 public event EventHandler<object> Tick 

So far WPF DispatcherTimer.Tick here public event EventHandler Tick

Also note that you do not need to use a standard named method to create an event handler. You can use lambda to do this in place:

 int timecounter = 10; DispatcherTimer timer = new DispatcherTimer(); public BlankPage() { this.InitializeComponent(); timer.Tick += (s,o)=> { timecounter--; if (timecounter == 0) { //disable all buttons here } }; } 
+2
source

All Articles