Thursday, 8 February 2007

Event Handling

Events are a way to allow a class to send a signal indicating that an event of some importance has taken place. Events are created from delegates using the event keyword. First, you declare the delegate.


delegate void StateChangedDelegate(object sender, EventArgs e);
The event is then declared as a member of the class:
 
public event StateChangedDelegate OnStateChangedHandler;
protected virtual
OnStateChanged(EventArgs e)
{
if (OnStateChangedHandler != null
)
{
OnStateChangedHandler(
this
, e);
}
}
Finally the calling class can subscribe to the event:
otherClass.OnStateChanged += new StateChangedDelegate(OtherClass_StateChanged);

No comments: