views:

64

answers:

1

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?

+3  A: 

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
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 Hein
And since you have to assign it a type, it can't be anonymous.
Richard Hein
@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
@Audrey Yeah, I misstated that, you're right. Nevertheless this won't compile.
Richard Hein
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<ConvertEventHandler, ConvertEventArgs>( 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 Hein
@Richard Hein: you're right, of course, so much for shooting from the hip :) I've updated my answer to reflect reality.
Chris Schmich