0

I'm trying to implement an extension method to a WPF FrameworkElement that allow users to execute an action only once when the element get loaded.

The idea here is that if the element is later unloaded then loaded again, the action doesn't get called a second time.

But I can't find out the proper syntax for the anonymous event handler to unregister itself when called...

public static void ExecuteOnceWhenLoaded(
        this FrameworkElement element,
        Action action)
{
    if(element.IsLoaded)
    {
        action();
    }
    else
    {
        RoutedEventHandler handler;
        handler = (s, e) =>
        {
            element.Loaded -= handler; // ERROR: handler is not initialized
            action();
        }
        element.Loaded += handler;
    }
}
Nicolas Repiquet
  • 9,097
  • 2
  • 31
  • 53
  • 1
    Extract handler's code into the private method and do normal subscribe/unsubscribe or see this post: [Unsubscribe anonymous method in C#](http://stackoverflow.com/a/183408/485076) – sll Mar 05 '13 at 14:32
  • 1
    @sll How the "action" parameter is supposed to be carried around if I "extract handler's code into a private method" ? – Nicolas Repiquet Mar 05 '13 at 14:38

3 Answers3

4

Maybe:

RoutedEventHandler handler = null;

Killo
  • 300
  • 1
  • 5
3

just do

    RoutedEventHandler handler = null; // Initialize handler with null
    handler = (s, e) =>
    {
        element.Loaded -= handler;
        action();
    }
    element.Loaded += handler;
herzmeister
  • 11,101
  • 2
  • 41
  • 51
0

That should be a compile time error because you are trying to unsubscribe a handler that is not created yet. In this scenario, it might be better to create a handler method and unsubscribe the handler on the first execution of the method? And there is no good reason why you should do an anonymous method while it is not a closure.