7

I am developing an application in windows 8 Visual studio 11, and I want to define an event handler for a DispatcherTimer instance as 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 widows 8 apps.

Would you please help me ?

Babak Fakhriloo
  • 2,076
  • 4
  • 44
  • 80

3 Answers3

8

almost had it :) You don't need to instantiate a new eventhandler object, you only need to point to the method that handles the event. Hence, an eventhandler.

        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 to read up on delegates to understand events Understanding events and event handlers in C#

Community
  • 1
  • 1
danielovich
  • 9,217
  • 7
  • 26
  • 28
3

Your code is expecting HandleTick to have two Object params. Not an object param and an EventArg param.

private void HandleTick(object s, object e)

NOT

private void HandleTick(object s,EventArgs e)

This is a change that took place for Windows 8.

dannybrown
  • 1,083
  • 3
  • 13
  • 26
2

WinRT makes use of Generics more than the standard .NET Runtime. DispatcherTimer.Tick as defined in WinRT is here:

public event EventHandler<object> Tick

While the WPF DispatcherTimer.Tick is here public event EventHandler Tick

Also note that you don't have to use the standard named method to create an Event Handler. You can use a lambda to do it 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
       }
    };
}
Michael Brown
  • 9,041
  • 1
  • 28
  • 37