将所有 UserControl 控件的单击事件绑定到父控件上的单个事件

Binding click events of all UserControl's controls to single event on parent Control

我正在尝试为我的用户控件实现一个事件处理程序,只要单击用户控件内的任何控件或用户控件本身就会触发一次单击。

public event EventHandler ClickCard
{
    add
    {
        base.Click += value;
        foreach (Control control in GetAll(this, typeof(Control)))
        {
            control.Click += value;
        }
    }
    remove
    {
        base.Click -= value;
        foreach (Control control in GetAll(this, typeof(Control)))
        {
            control.Click -= value;
        }
    }
}
public IEnumerable<Control> GetAll(Control control, Type type)
{
    var controls = control.Controls.Cast<Control>();

    return controls.SelectMany(ctrl => GetAll(ctrl, type))
                                      .Concat(controls)
                                      .Where(c => c.GetType() == type);
}

我修改了给定 here 的代码以绑定所有嵌套控件。这就是我绑定使用此用户控件的事件的方式:

private void feedbackCard1_ClickCard_1(object sender, EventArgs e)
{
    MessageBox.Show("Thank You!");
}

但点击用户控件内的任何控件或用户控件本身时,点击并未触发。

好吧,我想出了另一种方法:

Action clickAction;
public Action CardClickAction
{
    get
    {
        return clickAction;
    }
    set
    {
        Action x;
        if (value == null)
        {
            x = () => { };
        }
        else
            x = value;
        clickAction = x;
        pictureBox1.Click += new EventHandler((object sender, EventArgs e) =>
        {
            x();
        });
        label2.Click+= new EventHandler((object sender, EventArgs e) =>
        {
            x();
        });
        tableLayoutPanel3.Click += new EventHandler((object sender, EventArgs e) =>
                {
            x();
        });
    }
}

现在我们可以在使用此用户控件的表单上使用 CardClickAction 属性,如下所示:

Card1.CardClickAction = new Action(() =>
{
    //your code to execute when user control is clicked
});