How to add an event to a UserControl in C#?

后端 未结 6 2274
一向
一向 2020-11-27 05:04

I have a UserControl which contains 3 labels. I want to add an event for it, which occurs when the text of one of the labels changed.
I am using Visual Studio 2010

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 05:35

    First you should declare an event in your usercontrol for example:

    public event EventHandler TextOfLabelChanged;
    

    then you have to call the call back function that is bound to your event(if there's any) in runtime.You can do this by handling the TextChanged event of a label like this:

    public void LabelTextChanged(object sender,EventArgs e)
    {
    if(TextOfLabelChanged!=null)
    TextOfLabelChanged(sender,e);
    }
    

    You can have your own EventArgs object if you like.

    somewhere in your code you should bound your label TextChanged event to this method like this:

    _myLabel.TextChanged+=LabelTextChanged;
    

提交回复
热议问题