Reputation: 3218
I subscribe / create a custom Event Handler
with the following code:
myButton.Click += (sender, e) => MyButtonClick(sender, e, stuff1, stuff2);
I want to unsubscribe / remove and tried it like this:
myButton.Click += MyButtonClick;
But throws the following error:
No overload for 'MyButtonClick' matches delegate 'System.Windows.RoutedEventHandler'
And like this:
myButton.Click += MyButtonClick(sender, e, stuff1, stuff2);
But throws the following error:
Cannot implicitly convert type 'void' to 'System.Windows.RoutedEventHandler'
How do I unsubscribe / remove that same Event Handler
?
Upvotes: 2
Views: 2988
Reputation: 525
An example:
EventHandler myEvent = (sender, e) => MyMethod(myParameter);//my delegate
myButton.Click += myEvent;//suscribe
myButton.Click -= myEvent;//unsuscribe
private void MyMethod(MyParameterType myParameter)
{
//Do something
}
Upvotes: 0
Reputation: 21881
It's because your method does not match the signature of your event handler. In your first example you are creating an anon method with the correct signature that calls your method and adding the anon method as the event handler.
If you no not like this approach then simple create a wrapper method that fulfills the signature and calls the other method, which is essentially what you are doing e.g.
public void MyButtonClickWrapper(object sender, EventArgs e)
{
MyButtonClick(sender, e);
}
You can then wire this up in the normal way:
myButton.Click += MyButtonClickWrapper
myButton.Click -= MyButtonClickWrapper
Upvotes: 0
Reputation: 73482
When you use Lambda
you need to keep a reference of it to unsubscribe.
Try this
RoutedEventHandler handler = (sender, e) => MyButtonClick(sender, e, stuff1, stuff2);
myButton.Click += handler;//Subscribe
//Some more code
myButton.Click -= handler;//Unsubscribe
Upvotes: 5