How to call an event manually in C#?

前端 未结 6 1849
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-17 21:02

I have a USerControll in which i have a textbox. I use the usercontrol in my form, I want to do something when somebody presses enter on the textbox. how can I do it? if you

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-17 21:17

    Typically, the event invokation is wrapped in a method named something like "On[EventName]" which validates that the delgate has one or more targets (event is not null), and then invokes it with the sender and any applicable arguments...so something like this is the typical pattern:

    public event EventHandler SomethingHappened;
    protected void OnSomethingHappend(EventArgs e)
    {
        if (SomethingHappened != null)
            SomethingHappened(this, e);
    }
    

    Anything that needs to raise that event invokes that method (assuming its accessible).

    If you simply want to pass the event along, then as a UserControl, you can probably just invoke the base "On[Event]" method, which is likely exposed. You can wire up the event handlers, too, to directly pass the event from a child control as the event of the parent control...so that txtFoo.KeyPress simply invokes the OnKeyPress method of the parent control.

提交回复
热议问题