Can an event handler refer to itself without reflection?
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.
Ok, found it.
Ok, found it. The reason I couldn't get it to work was I was doing this...
RoutedEventHandler Control_Loaded = (s2, e2) =>
{
control.Loaded -= Control_Loaded;
WireUpScrollViewerEvents(control);
};
...when I should have been doing this...
RoutedEventHandler Control_Loaded = null; // <-- It's now declared before it's set, which is what we need
Control_Loaded = (s2, e2) =>
{
control.Loaded -= Control_Loaded;
WireUpScrollViewerEvents(control);
};
This is because you have to actually declare the variable before you can use it, and I was trying to use it as part of the declaration. This fixes that.
链接地址: http://www.djcxy.com/p/51474.html下一篇: 一个事件处理程序可以不经反射就自引