1.首先在usercontrol后台添加如下代码:
public partial class MyControl: UserControl
{
//添加事件代理
public event EventHandler AX;
//在需要响应的事件中添加
private void MyControl_MouseClick(object sender, MouseEventArgs e)
{
if (AX != null)
{
AX(this, e);
//Or use the following sentence code.
//AX(this, new EventArgs());
}
}
}
2.在窗体或页面添加一个用户控件,在Page_Load或Form_Load事件中添加:
private void FrmRBD_Load(object sender, EventArgs e)
{
MyControl1.AX += new EventHandler(Event_AX);
}
protected void Event_AX(object sender, EventArgs e)
{
MessageBox.Show("Event has occur!<br/>");
}
以添加自定义按钮的Click事件举例,这里需要注意的是,如果自定义控件上是多个控件的组合,比如Picture控件上有个Label控件,这样子的话,需要在 public partial class MyControl: UserControl 中把Picture和Label的Click都映射到MyControl的Click,否则事件也不会调用!