Andrew Simpson
Andrew Simpson

Reputation: 7314

Is it possible to put an event handler directly to a function

I have a wpf c#app.

I have an event declared in my user control and my user-control is already loaded into my main window.

In my code {somewhere appropriate) I define my event handler to a function like so:

    MyUserControl.MyEvent += Myfunction;

...

void Myfunction(object someData)
{
   //do something
}

To make things 'cleaner' i would like to do something like this instead:

MyUserControl.MyEvent +=> Myfunction(someData);

obviously, this does not compile but i put it in to try and illustrate what i want...

Upvotes: 1

Views: 118

Answers (1)

juharr
juharr

Reputation: 32266

I think you are trying to create a lambda for your event

MyUserControl.MyEvent += (object o) => Myfunction(someData);

The trick is that it must match the delegate signature for the event, which in your case would be a method that takes an object and doesn't return anything. Note that by doing this you are ignoring the object that your event is sending out.

Upvotes: 3

Related Questions