6

Possible Duplicate:
How do I Unregister 'anonymous' event handler

I have code like this:

        Binding bndTitle = this.DataBindings.Add("Text", obj, "Title");
        bndTitle.Format += (sender, e) =>
        {
            e.Value = "asdf" + e.Value;
        };

How do I now disconnect the Format event?

Community
  • 1
  • 1
AngryHacker
  • 59,598
  • 102
  • 325
  • 594

1 Answers1

3

You can't do that, unfortunately. You could create a local to hold the lambda if you remove the event in the same scope:

Binding bndTitle = this.DataBindings.Add("Text", obj, "Title");
EventHandler handler = (sender, e) =>
{
    e.Value = "asdf" + e.Value;
};

bndTitle.Format += handler;
// ...
bndTitle.Format -= handler;
Chris Schmich
  • 29,128
  • 5
  • 77
  • 94
  • You cannot "Cannot assign lambda expression to an implicitly-typed local variable". It would have to be ConvertEventHandler handler = (sender, e) => { e.Value = "asdf" + e.Value; }; – Richard Anthony Hein Sep 20 '10 at 23:10
  • And since you have to assign it a type, it can't be anonymous. – Richard Anthony Hein Sep 20 '10 at 23:15
  • @Richard Hein you are wrong, method can be anonymous but have a type (be converted to delegate). Anonymousity of method (lambda) means that it can't be refered by name. – Andrey Sep 20 '10 at 23:28
  • @Audrey Yeah, I misstated that, you're right. Nevertheless this won't compile. – Richard Anthony Hein Sep 20 '10 at 23:36
  • In the case of this situation, Rx is very useful. Using Rx you can do this: Binding bndTitle = this.DataBindings.Add("Text", obj, "Title"); var handler = Observable.FromEvent( h => new ConvertEventHandler(h), h => bndTitle.Format += h, h => bndTitle.Format -= h); disposableHandler = handler.Subscribe(e => e.EventArgs.Value = "asdf" + e.EventArgs.Value); Then you keep a reference to disposableHandler, and call Dispose() whenever you like. – Richard Anthony Hein Sep 20 '10 at 23:38
  • @Richard Hein: you're right, of course, so much for shooting from the hip :) I've updated my answer to reflect reality. – Chris Schmich Sep 21 '10 at 00:25