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;
}
}