views:

280

answers:

2

I have a base UserControl (BaseControl.cs) which has an OK and Cancel buttons on it. When the buttons are clicked, an event is fired. Typically other UserControl objects inherit from the BaseControl. Finally the descendant UserControl objects are placed on a WinForm, where they hook into the events for clicking Ok/Cancel buttons.

My question is this: in the descendant control, I'd like to intercept the events (to run some validation). How can hook into (or intercept) the these events?

Thanks.

A: 

You would typically create a protected virtual Validate() method, which gets called in the BaseControl's event handlers. Then in the DescendantControl you'd override the Validate() method.

Here's some documentation on Inheritance.

Kon
+4  A: 

The standard pattern for implementing events is to use a virtual "OnXxx" method, like this:

public event EventHandler OkClick;
protected virtual void OnOkClick(EventArgs e)
{
    if (OkClick != null) OkClick(this, e);
}

Now any time your base control wants to fire the "OkClick" event, it simply calls:

OnOkClick(EventArgs.Empty);

This means that descendants of your base control can override OnOkClick like this:

protected override void OnOkClick(EventArgs e)
{
    // do some stuff before the event is fired
    base.OnOkClick(e);
    // do some stuff after the event is fired
}

Note that the framework design guidelines actually state that you should implement the "OnXxx" method in such a way that the event is fired even if the descendant classes forget to call the base method. I don't really know a good way to do that, and I'm sure most people ignore this guideline.

Matt Hamilton