Cannot implicitly convert type System.EventHandler to System.EventHandler<object> error
Asked Answered
N

4

8

I am trying to implement a Timer in windows phone app.It works fine in Windows Phone App(Silverlight) but it isnt working in Windows Phone Blank App.But it gives me following error-

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

This is my code -

namespace Timer
{
    public partial class MainPage : Page
    {           
        DispatcherTimer mytimer = new DispatcherTimer();
        int currentcount = 0;
        public MainPage()
        {
            InitializeComponent();

            mytimer = new DispatcherTimer();
            mytimer.Interval = new TimeSpan(0, 0, 0, 1, 0);
            mytimer.Tick += new EventHandler(mytime_Tick);
              //HERE error comes Cannot implicitly convert type System.EventHandler to System.EventHandler<object>
        }

        private void mytime_Tick(object sender,EventArgs e)
        {
            timedisplayBlock.Text = currentcount++.ToString();    
        }

        private void startButton_Click(object sender, RoutedEventArgs e)
        {
            mytimer.Start();
        }
    }
}

I tried Cannot implicitly convert type 'System.EventHandler' to 'System.EventHandler<object>' for storyboard complete

But it even helped.How can I fix this error?

Namely answered 15/2, 2015 at 2:43 Comment(0)
B
15

Referencing the method handler for the event directly will infer the type, satisfying the generic type declaration requirement.

mytimer.Tick += mytime_Tick;

Alternatively, explicitly declaring the generic type and using the generic EventHandler constructor,

mytimer.Tick += new EventHandler<object>(mytime_Tick);

would do the trick.

In addition, according to the documentation, your handler has the wrong signature. It should be:

private void mytime_Tick(object sender,object e)
{
    timedisplayBlock.Text = currentcount++.ToString();    
}
Bore answered 15/2, 2015 at 2:48 Comment(0)
F
11

Just write mytimer.Tick += then press TAB Key two times it will fix your bug.

Fob answered 21/1, 2016 at 20:25 Comment(0)
P
2

If you want to avoid a conversion, you can always do the following:

mytimer.Tick += (s, ev) => { mytime_Tick(s, ev); }

It's very useful if you are validating nullables:

mytimer.Tick += (s, ev) => { mytime_Tick?.Invoke(s, ev); }

Regards, Nicholls

Phreno answered 31/5, 2017 at 7:13 Comment(0)
N
0

As the error message is trying to tell you, you need to create an EventHandler<object>.

Or, better yet, leave the delegate type out entirely and just add the method name.

Nerve answered 15/2, 2015 at 2:48 Comment(1)
Both of this is giving me this same new error- No overload for mytime_Tick` matches delegate `System.EventHandler<object>Namely

© 2022 - 2024 — McMap. All rights reserved.