0

I have a class StripButton which inherits from Label. I have overriden the onClick method. The user of this class also assigns events to the onClick eventhandler. I have noticed that the overriden method gets fired last. I want the overriden method to fire first. How can I do that?

4

1 回答 1

1

The Click handler of a StripButton on your Form will fire when the base.OnClick method in the OnClick handler is called in your UserControl. So if you want your UserControl's OnClick code to run before the Click handler code runs on your Form, call base.OnClick last in your UserControl's OnClick handler. Conversely, if you want your Form's Click code to run after your UserControl's OnClick code, call base.OnClick first in your UserControl's OnClick handler.

It's probably easiest to illustrate with the simplest example:

// Your UserControl.
class StripButton : Label
{
    protected override void OnClick(EventArgs e) {
        Console.WriteLine("This runs before the Click handler on the parent form.");
        base.OnClick(e);
        Console.WriteLine("This runs after the Click handler on the parent form.");
    }
}

// On your form.
private void stripButton1_Click(object sender, EventArgs e) {
    Console.WriteLine("stripButton1_Click on form");
}

If you run this you'll see the following in the Output Window:

This runs before the Click handler on the parent form.
stripButton1_Click on form
This runs after the Click handler on the parent form.

Hopefully that answers your question.

于 2013-07-20T07:01:59.260 回答