如何为用户控件添加事件

 

Windows 窗体支持三种用户定义的控件:复合、扩展和自定义,复合控件是封装在公共容器内的 Windows 窗体控件的集合。这种控件有时称为“用户控件”,包含的控件称为“构成控件”。

 

控件代码:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Drawing;

using System.Data;

using System.Text;

using System.Windows.Forms;

 

namespace WindowsControlLibrary1

{

    public partial class UserControl1 : UserControl

    {

        public delegate void TextBoxChangedHandle(string message);

        public delegate void MyButtonClickHandle();

 

        public event TextBoxChangedHandle TextBoxChanged;

        public event MyButtonClickHandle MyButtonClick; 

 

        public UserControl1()

        {

            InitializeComponent();

        }

 

        private void textBox1_TextChanged(object sender, EventArgs e)

        {

            TextBoxChanged(this.textBox1.Text);  

        }

 

        private void button1_Click(object sender, EventArgs e)

        {

            if (MyButtonClick != null)
            {
                MyButtonClick();
            }
        }

    }

}

 

 

调用窗体:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

 

namespace WindowsApplication1

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        private void userControl11_MyButtonClick()

        {

            MessageBox.Show("你点击用户控件中的按钮!" );  

        }

 

        private void userControl11_TextBoxChanged(string message)

        {

            MessageBox.Show("你改变了用户控件中TextBox的值:" + message); 

        }

 

    }

}

你可能感兴趣的:(用户)