Last Updated: February 25, 2016
· keboo

Self-unregistering event handler

There are time when you only want to handle an event the first time that it is raised. There are plenty of way to do this, but I find that being able to create a handler that will automatically un-register itself when it is called, makes the code simple and compact.

Here is an example of how to implement the self un-registering event handler

public MainWindow()

    RoutedEventHandler handler = null;
    handler = (sender, e) =>
                        Loaded -= handler;

                        //Do something here
    Loaded += handler;

To generalize the process, first you declare an event handler delegate that matched the delegate type of the event. In my example, and many events in WPF controls, the events will require a RoutedEventHandler delegate. You must set this delegate to a value, since you will be using the variable inside of the anonymous method. I like to use null as the value since this value will not be used.

The second step is to set the delegate to an anonymous method, with the first line un-registering the event.

The last step is the hook up the event handler to your event.

For those of you using ReSharper, this can easily be done using code templates.

Below is an example of the template I created to make writing these handlers easy.



Say Thanks