Monday, August 22, 2011

Small things learned today: Raise Base Class Event in Derived Classes.

I have to admit that I did not know this before today.

If I have a base class that have controls, I can not directly subscribe to the events invoked by the controls of this class (or, more generally, I can not directly subscribe to any events declared by the base class, but in my case I was interested in button click events).

I have to use a simple technique to achieve my goal: In the base class, provide and EventHandler (my button is called "Run Draw", hence the names)

public event EventHandler RunDrawClicked;
protected virtual void OnRunDrawClicked(EventArgs e)
{
EventHandler handler = RunDrawClicked;
if (handler != null)
{
handler(this, e);
}
}

base class can subscribe to its own button click, of course

protected void btnRunDraw_Click(object sender, System.EventArgs e)
{
MessageBox.Show("base");
OnRunDrawClicked(e);
}

and the derived class can subscribe to the event provided by the base class

protected override void OnRunDrawClicked(EventArgs e)
{
MessageBox.Show("derived");
base.OnRunDrawClicked(e);
}

Reference:

How to: Raise Base Class Events in Derived Classes by . Also posted on my website

No comments: