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