[英]How to get Usercontrol object 'X' from X's Button(i.e. Button inside the X) onclick event
大家好,我正在.Net C#中的Windows窗體應用程序上工作。
現在,我有一個帶有一個按鈕的用戶控件。 但是,我必須以主要形式而不是在用戶控件本身內部編寫單擊處理程序。 現在,我想知道是否仍然可以在Button的單擊處理程序中獲取User-control對象。 由於我不得不以相同的形式多次使用它們。 我想知道單擊了哪個用戶控件的按鈕。
User Control
Button
謝謝 :)
這是UserControl引發自定義事件的示例,該事件傳遞了單擊了Button的源UserControl:
SomeUserControl:
public partial class SomeUserControl : UserControl
{
public event ButtonPressedDelegate ButtonPressed;
public delegate void ButtonPressedDelegate(SomeUserControl sender);
public SomeUserControl()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (ButtonPressed != null)
{
ButtonPressed(this); // pass the UserControl out as the parameter
}
}
}
表格1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
someUserControl1.ButtonPressed += new SomeUserControl.ButtonPressedDelegate(SomeUserControl_ButtonPressed);
someUserControl2.ButtonPressed += new SomeUserControl.ButtonPressedDelegate(SomeUserControl_ButtonPressed);
someUserControl3.ButtonPressed += new SomeUserControl.ButtonPressedDelegate(SomeUserControl_ButtonPressed);
}
void SomeUserControl_ButtonPressed(SomeUserControl sender)
{
// do something with "sender":
sender.BackColor = Color.Red;
}
}
您可以使用事件:
public delegate void ButtonClicked();
public ButtonClicked OnButtonClicked;
然后,您可以在任何地方訂閱事件,例如,在MainForm中,您有一個名為demo的用戶控件。
demo.OnButtonClicked +=()
{
// put your actions here.
}
只需遍歷.Parent()鏈,直到找到與UserControl類型相同的控件即可。 在下面的示例中,UserControl的類型為SomeUserControl
:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
someUserControl1.button1.Click += new EventHandler(button1_Click);
someUserControl2.button1.Click += new EventHandler(button1_Click);
someUserControl3.button1.Click += new EventHandler(button1_Click);
}
void button1_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
Control uc = btn.Parent;
while (uc != null && !(uc is SomeUserControl))
{
uc = uc.Parent;
}
uc.BackColor = Color.Red;
MessageBox.Show(uc.Name);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.