事件处理程序可以在没有反射的情况下引用它

时间:2012-09-13 17:53:31

标签: c# events event-handling lambda anonymous-methods

  

可能重复:
  Unsubscribe anonymous method in C#
  Single-shot event subscription

是否可以从事件处理程序本身获取对事件处理程序的引用,以便您可以从调用它的事件中取消它?

例如,我喜欢制作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调用中匿名删除它。

1 个答案:

答案 0 :(得分:2)

好的,找到了。

好的,找到了。我无法让它工作的原因是我这样做......

RoutedEventHandler Control_Loaded = (s2, e2) =>
{
    control.Loaded -= Control_Loaded;
    WireUpScrollViewerEvents(control);
};

......当我应该这样做的时候......

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

这是因为您必须在使用它之前实际声明该变量,并且我试图将其用作声明的一部分。这解决了这个问题。