[英]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.