C# 如何获取Usercontrol对象';X';从X';s按钮(即X内的按钮)onclick事件
大家好,我正在.NETC#中开发一个Windows窗体应用程序 现在我有一个用户控件,里面有一个按钮。 但是,我必须在主窗体中编写on-click处理程序,而不是在用户控件本身中编写。 现在我想知道是否还有其他方法可以在按钮的点击处理程序中获取用户控件对象。因为我不得不以同样的形式多次使用它们。我想知道单击了哪个用户控件的按钮C# 如何获取Usercontrol对象';X';从X';s按钮(即X内的按钮)onclick事件,c#,user-controls,onclick,handler,C#,User Controls,Onclick,Handler,大家好,我正在.NETC#中开发一个Windows窗体应用程序 现在我有一个用户控件,里面有一个按钮。 但是,我必须在主窗体中编写on-click处理程序,而不是在用户控件本身中编写。 现在我想知道是否还有其他方法可以在按钮的点击处理程序中获取用户控件对象。因为我不得不以同样的形式多次使用它们。我想知道单击了哪个用户控件的按钮 User Control Button 谢谢:)您可以使用事件: public delegate void ButtonClicked(); public Button
User Control
Button
谢谢:)您可以使用事件:
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);
}
}
下面是UserControl引发自定义事件的示例,该事件传递单击按钮的源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;
}
}
六羟甲基三聚氰胺六甲醚。。奇怪的是,它显示了()附近的语法错误。它的意思是“无效的表达式项'”,使用VisualStudioIntellisence(type+=然后type tab键),代码只是一个骨架!谢谢你的回答:)但是我在等待更多的答案。。。在那之后,我将把它标记为答案。这样做的必要性表明了一个非常糟糕的设计。最好让UserControl引发一个自定义事件,并将UserControl作为该事件的参数传递出去。