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.
The standard pattern for implementing events is to use a virtual ‘OnXxx’ method, like this:
Now any time your base control wants to fire the ‘OkClick’ event, it simply calls:
This means that descendants of your base control can override OnOkClick like this:
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.