Possible Duplicate:
Unsubscribe anonymous method in C#
Single-shot event subscription
Is it possible to get a reference to an event handler from within the event handler itself so you can unhook it from the event that called it?
For instance, I'd love to make the control.Loaded event point to a Lambda, but if I did, I don't know what to pass to the unhook (-=) call.
Here's an excerpt of the code:
private static void IsEnabled_Changed(object sender, DependencyPropertyChangedEventArgs e)
{
var control = (Control)sender;
if(control.IsLoaded)
WireUpScrollViewerEvents(control);
else
control.Loaded += Control_Loaded;
}
private static void Control_Loaded(object sender, RoutedEventArgs e)
{
var control = (Control)sender;
control.Loaded -= Control_Loaded; // <-- How can I do this from a lambda in IsEnabled_Changed?
WireUpScrollViewerEvents(control);
}
private static void WireUpScrollViewerEvents(Control control, bool attach)
{
var scrollViewer = Utils.FindFirstVisualChild<ScrollViewer>(control);
if(scrollViewer == null) return;
var attachEvents = GetIsEnabled(control);
if(attachEvents)
{
scrollViewer.PreviewDragEnter += ScrollViewer_PreviewDragEnter;
scrollViewer.PreviewDragOver += PreviewDragOver;
}
else
{
scrollViewer.PreviewDragEnter -= ScrollViewer_PreviewDragEnter;
scrollViewer.PreviewDragOver -= PreviewDragOver;
}
}
The only reason Control_Loaded is an actual method is because of the 'control.Loaded -= Control_Loaded' line. Iām wondering if we can anonymous-lambda away it from within the IsEnabled_Changed call directly.