Winforms user controls custom events

前端 未结 2 2048
灰色年华
灰色年华 2020-12-08 10:50

Is there a way to give a User Control custom events, and invoke the event on a event within the user control. (I\'m not sure if invoke is the correct term)

p         


        
2条回答
  •  爱一瞬间的悲伤
    2020-12-08 11:32

    I believe what you want is something like this:

    public partial class Sample: UserControl
    {
        public event EventHandler TextboxValidated;
    
        public Sample()
        {
            InitializeComponent();
        }
    
    
        private void TextBox_Validated(object sender, EventArgs e)
        {
            // invoke UserControl event here
            if (this.TextboxValidated != null) this.TextboxValidated(sender, e);
        }
    }
    

    And then on your form:

    public partial class MainForm : Form
    {
        private Sample sampleUserControl = new Sample();
    
        public MainForm()
        {
            this.InitializeComponent();
            sampleUserControl.TextboxValidated += new EventHandler(this.CustomEvent_Handler);
        }
        private void CustomEvent_Handler(object sender, EventArgs e)
        {
            // do stuff
        }
    }
    

提交回复
热议问题