欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

c# winform 用户控件usercontrol 事件在父窗体触发

程序员文章站 2022-06-08 18:43:07
...
User control:

[Browsable(true)] [Category("Action")] 
[Description("调用用户按钮事件")]
public event EventHandler ButtonClick;

protected void Button1_Click(object sender, EventArgs e)
{
    //bubble the event up to the parent
    if (this.ButtonClick!= null)
        this.ButtonClick(this, e);               
}




Form:

UserControl1.ButtonClick += new EventHandler(UserControl_ButtonClick);

protected void UserControl_ButtonClick(object sender, EventArgs e)
{
    //handle the event 
}
推荐一种更简洁的方法

UserControl:
public System.Windows.Forms.Panel panel;



Winform:
UserControl item = new UserControl();
item.panelTitle.Click += panel1_Click;

protected void panel1_Click(object sender, EventArgs e)
{
   var form = (UserControl)(((Panel)sender).Parent);
   Method(sender, e);
}

 

相关标签: c#