0

大家好,我正在使用 .Net C# 开发 Windows 窗体应用程序。

现在我有一个用户控件,里面有一个按钮。但是我不得不在主窗体中而不是在用户控件本身中编写点击处理程序。现在我想知道是否有任何方法可以在按钮的单击处理程序中获取用户控件对象。因为我不得不以相同的形式多次使用它们。我想知道单击了哪个用户控件的按钮。

User Control
Button

谢谢你 :)

4

3 回答 3

1

这是 UserControl 引发自定义事件的示例,该事件传递了单击按钮的源 UserControl:

一些用户控制:

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;
    }
}
于 2013-05-19T18:23:03.450 回答
0

You can use event:

public delegate void ButtonClicked();
public ButtonClicked OnButtonClicked;

You can then subscribe the event anywhere, for instance, in your MainForm, you have a user control called demo;

demo.OnButtonClicked +=() 
{
   // put your actions here.
}
于 2013-05-19T13:41:07.573 回答
0

只需遍历 .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);
    }

}
于 2013-05-19T15:38:34.073 回答