2

I've created an extension method that works just like I wanted. I've noticed that somehow the party and property parameters are 'copied' into the lambda expression. This way I do not need to maintain a custom list of editor/party/property associations.

However, I need to reset the ButtonEdit's ButtonClick event. Since this one is anonymous I cannot use the -= opertor either.

So, my question is - how do I rewrite this method so that the delegate can be removed? Or, which other approach can I use to handle a specific event handler with extra parameters (such as party and property)?

private static void SetupAddressButtonClickEvent(this ButtonEdit editor, Party party, string property)
{
    editor.SetAddressDisplayText(party, property);
    editor.ButtonClick += (sender, e) =>
        {
            party.ShowAddressLookupDialog(property);
            editor.SetAddressDisplayText(party, property);
        };
}

Thank you, Stefan

Stefan
  • 75
  • 4

1 Answers1

3
Action<object,EventArgs> myaction = (sender, e) =>
        {
            party.ShowAddressLookupDialog(property);
            editor.SetAddressDisplayText(party, property);
        };

editor.ButtonClick += myaction;
editor.ButtonClick -= myaction;

edit option 2 could be:

class MyEventHandler
{
  ... _property;
  ... _party;
  ... _editor;
  public MyEventHandler(... property, ... party, ... editor)
  {
    _property = property;
    _party = party;
    _editor = editor;
  }

  public void Handler(object sender, EventArgs e)
  {
    _party.ShowAddressLookupDialog(_property);
    _editor.SetAddressDisplayText(_party, _property);
  }
}

and then use it like this:

var handler = new MyEventHandler(party,property,editor);
editor.ButtonClick += handler.Handler;

I'm not sure how much this will help you because I don't 100% understand what you're trying to solve.

vanja.
  • 2,532
  • 3
  • 23
  • 39
  • So I need to store a list of ButtonEdit/Action associations internally? – Stefan Jan 29 '10 at 08:46
  • I don't know where you are trying to remove the action so I can't really help with how to remove it. Are you trying to remove it in another click handler? – vanja. Jan 29 '10 at 09:00
  • I remove the event handler before re-binding the controls on the form. The event handler will reference a disposed object if I don't reset it. Your option 2 looks interesting though. Does this approach have a name? – Stefan Jan 29 '10 at 09:12
  • In option 1, the event has to be unsubscribed _inside_ of the handler, otherwise the event will hardly ever fire. ;_) ... I asked a similar question these days: http://stackoverflow.com/questions/2147116/event-handling-with-an-anonymous-delegate – herzmeister Jan 29 '10 at 10:10
  • I'm afraid I haven't seen option 2 documented anywhere. Option 1 was really a partial code sample that just showed the mechanism but would require you to separate the event setter and de-setter. – vanja. Feb 01 '10 at 01:15