How to call an event manually in C#?

前端 未结 6 1850
佛祖请我去吃肉
佛祖请我去吃肉 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:30

    If you are using WPF, you might be able to use RaiseEvent: http://msdn.microsoft.com/en-us/library/system.windows.uielement.raiseevent.aspx

    But this is wrong for what you want to do.

    You should bubble the event.

    class MyControl : UserControl {
        public KeyDownEventHandler KeyDown;
    
        private void OnTextBoxKeyDown(object sender, EventArgs e){ KeyDown.Invoke(sender, e); }
    }
    

    Then listen to KeyDown from your form. Please excuse mistakes in the naming of the various elements / events.

提交回复
热议问题