Small Tip Removing lambda expression event handlers (no reflection)

Sometimes you need to activate an event just once and then you have to remove and you like using lambda expressions instead of adding and adding methods, I didn’t realize that you can do the following to remove an event handler

RoutedEventHandler Routed = null;
Routed = (s,e)=>
    {
        MessageBox.Show("removing event handler");
        (s as Button).Click -= Routed;
    };
this.button1.Click += Routed;

And that is all, you will be sure that every time is added when is called is remove without using reflection.

Advertisements

2 thoughts on “Small Tip Removing lambda expression event handlers (no reflection)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s