How to...

  • Thread starter Thread starter Jacek Jurkowski
  • Start date Start date
J

Jacek Jurkowski

.... clear all delegates assigned to an event.

this.button1.click += delegate{...};
this.button1.click += new EventHandlet{this.OnClick(...);}

how to clear a "click" events or suspend
its execution on click?
 
Only the button can clear its own events.
You could manually unsubscribe each handler, but that requires you to keep a
reference to the anonymous method.

Perhaps an easier option:

this.button1.enabled = false;

?

Alternatively, if you need to keep the UI side "as is", you could perhaps
inherit from the button, and override the OnClick method, to only call
base.OnClick if a certain condition is met (i.e. not suspended). You could
also (instead) test such a condition in the handlers themselves.

Marc
 
Jacek,

Only the object publishing the event can clear the event. Beside the obvious
logical reason techically the multicast delegate, backing up the event, is
private inside (the button in this case) and no other code but the button
itself has access to it. For the outside world the event is just pair of
methods - add and remove (the remove needs parameter what to remove so it
can be used to remove only handlers that are known to the removing code).

One more remark. Don't use anonymous event handlers if you plan to
unsubscribe form the event. Since the handler is anonymouse it cannot be
directly removed. They can be removed only by keeping reference to the
delegate created using the anonymous method. It kind of defeat the purpose
of the anonymous method, but one can still benefit from the context in which
the handler is created.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top