I created the following code:
private struct StackItem
{
public EventHandler theEvent, theHandler;
public StackItem(EventHandler theEvent, EventHandler theHandler)
{
this.theEvent = theEvent;
this.theHandler = theHandler;
}
}
protected void AddHandler(EventHandler theEvent, EventHandler theHandler)
{
theEvent += theHandler; // add handler to event
stack.Push(new StackItem(theEvent, theHandler)); // note the fact that we
did so
}
public virtual void Dispose()
{
while (stack.Count 0)
{
StackItem si = (StackItem)stack.Pop();
si.theEvent -= si.theHandler; // remove the handler from the event
}
}
So that my derived classes can register for various events of various
controls on my form without having to make certain to add both the subscribe
and unsubscribe lines of code. However, the following code:
AddHandler(form.listView.SizeChanged, new
System.EventHandler(this.listView_SizeChanged));
gives the following error:
"The event 'System.Windows.Forms.Control.SizeChanged' can only appear on the
left hand side of += or -="
I assume this is some attribute of the SizeChanged member of the various
stock controls. Is there any way around this?
Why do I need to unsubscribe? Because I'm using objects to implement various
states in my application. When the app changes states it needs to unhook the
current state object from all events so that the new state can take over.