[英]Get event from dynamically added button in UserControl
我想获取UserControl
Button
的clicked事件,并在窗体中动态添加该UserControl
。 我希望在添加UserControl
的Form
中引发事件。 如果有人可以建议我正确的方法,那将非常有帮助。
您需要在用户控件中公开事件,然后在将用户控件添加到表单中时对其进行订阅。 例如:
public partial MyUserControl:Control
{
public event EventHandler ButtonClicked;
private void myButtonClick(object sender, EventArgs e)
{
if (this.ButtonClicked != null)
this.ButtonClicked(this, EventArgs.Empty);
}
}
public partial MyForm:Form
{
private void MethodWhereYouAddTheUserControl()
{
var myUC = new MyUserControl();
myUC += myUC_ButtonClicked;
// code where you add myUC to the form...
}
void myUC_ButtonClicked(object sender, EventArgs e)
{
// called when the button is clicked
}
}
我猜您正在使用Winforms来指代您的标题。
您可以采取什么措施来转发Click
事件。
因此,在您的UserControl的ctor中
public class MyUserControl
{
public event EventHandler MyClick;
private void OnMyClick()
{
if (this.MyClick != null)
this.MyClick(this, EventArgs.Empty);
}
public MyUserControl()
{
this.Click += (sender, e) => this.OnMyClick();
}
}
将您自己的事件添加到自定义用户控件中。
在客户用户控件内部,添加按钮后,还应附加(内部)事件处理程序,该事件处理程序将引发您自己的公共事件,并通过某种方式告诉事件处理程序单击了哪个按钮(您很可能需要自己的按钮)委托这里)。
完成后,您的窗体可以添加其自己的事件处理程序,就像您将一个事件处理程序添加到标准控件一样。
重新阅读您的问题,这可能不是确切的结构(按钮是固定的,但用户控件是动态添加的?)。 无论如何,它应该几乎相同,只是在创建时添加事件处理程序的位置/何时不同。
使用一个静态按钮,可以轻松得多-假设您使用的是Windows Forms:
在自定义用户控件中:
public event EventHandler ButtonClicked; // this could be named differently obviously
...
public void Button_OnClick(object sender, EventArgs e) // this is the standard "on button click" event handler created using the form editor
{
if (ButtonClicked != null)
ButtonClicked(this, EventArgs.Empty);
}
以您的形式:
// create a new user control and add the event
MyControl ctl = new MyControl();
Controls.Add(ctl);
ctl.ButtonClicked += new EventHandler(Form_OnUserControlButtonClicked); // name of the event handler in your form that's called once you click the button
...
private void Form_OnUserControlbuttonClicked(object sender EventArgs e)
{
// do whatever should happen once you click the button
}
当您将usercontrol
添加到form
,请注册click事件(如果它是public
) usercontrol.button.Click += new EventHandler(usercontrolButton_Click);
在usercontrol
注册按钮的Click
事件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.