是否可以从事件处理程序本身中获取对事件处理程序的引用,以便您可以从调用它的事件中解开它?
例如,我很想将 control.Loaded 事件指向一个 Lambda,但如果我这样做了,我不知道将什么传递给 unhook (-=) 调用。
这是代码的摘录:
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;
}
}
Control_Loaded 是一种实际方法的唯一原因是因为“control.Loaded -= Control_Loaded”行。我想知道我们是否可以直接从 IsEnabled_Changed 调用中匿名 lambda。