UserControl 和 WinForm 的互動

来源:互联网 发布:安装淘宝的npm镜像 编辑:程序博客网 时间:2024/06/06 05:52

UserControl 和 WinForm 的互動

之前有一個問題是,我用了一個自訂控制項,當它觸發了之後,如何和它的Form互動?這也要我想了好久,解法還滿簡單的。
1.public event EventHandler myClick; 先定一個自訂的事件在User Control 中
2.在你要發生的事件(Event)中,叫用你自訂的事件
EX:
private void button1_Click(object sender, EventArgs e)
   {
    if (myClick != null)
    {
     myClick(this, e);
    }
    else
    {
     throw new Exception("12345");
    }
   }
3.在有需要和這一個控制項發生關係的地方,訂閱它
EX: 
private void Form1_Load(object sender, EventArgs e)
{
 this.userControl11.myClick += new EventHandler(myButtonHandler); 
}
4.所以,你就可以在你目前的程式中使用到自訂控制項的事件,並接收到從控制項傳上來的事件和,取得控制項中的值。
EX:
public void myButtonHandler(object sender, EventArgs e)
  { 
   UserControl1 xx = sender as UserControl1;
   MessageBox.Show(xx.getTextBoxText()); 
  }
0 0
原创粉丝点击