首先拖一個用戶控件:
public partial class MyControl : UserControl
{
public MyControl()
{
InitializeComponent();
}
public event EventHandler<MyButtonEvent> MyBtnClick;//定義一個用戶控件的事件
//用戶控件中通過Button的Click事件觸發自定義事件
private void button1_Click(object sender, EventArgs e)
{
//將用戶控件中TextBox的文本內容,傳給事件MyButtonEvent
MyBtnClick(sender, new MyButtonEvent(this.textBox2.Text));
}
}
上面這個類是用戶控件的
public class MyButtonEvent : EventArgs
{
private object sender;
public MyButtonEvent()//空構造,必須有
{
}
public MyButtonEvent(object sender)//帶參數的構造
{
this.sender = sender;
}
public string GetStr()//外部通過e點出來的方法
{
return sender.ToString();
}
}
先生成一下解決方案,你就會看到在Form中拖入的用戶控件就會多了一個MyBtnClick事件,雙擊就和我們平常用的Click事件一樣用了。
在Form窗體中拖入一個上面建好的用戶控件MyControl 和一個TextBox->textBox1
private void myControl1_MyBtnClick(object sender, MyButtonEvent e)//自定義事件
{
this.textBox1.Text = e.GetStr();
}
以上代碼通過自定義事件的形式,將用戶控件中的值傳給父窗體