您将需要连接您关心在用户控件中捕获的事件,并通过用户控件本身的一些自定义事件属性发布它们。一个简单的例子是包装一个按钮点击事件:
// CustomControl.cs
// Assumes a Button 'myButton' has been added through the designer
// we need a delegate definition to type our event
public delegate void ButtonClickHandler(object sender, EventArgs e);
// declare the public event that other classes can subscribe to
public event ButtonClickHandler ButtonClickEvent;
// wire up the internal button click event to trigger our custom event
this.myButton.Click += new System.EventHandler(this.myButton_Click);
public void myButton_Click(object sender, EventArgs e)
{
if (ButtonClickEvent != null)
{
ButtonClickEvent(sender, e);
}
}
然后,在使用该控件的表单中,您可以像其他任何方式一样连接事件:
// CustomForm.cs
// Assumes a CustomControl 'myCustomControl' has been added through the desinger
this.myCustomControl.ButtonClickEvent += new System.EventHandler(this.myCustomControl_ButtonClickEvent);
myCustomControl_ButtonClickEvent(object sender, EventArgs e)
{
// do something with the newly bubbled event
}