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);
}