-1

I am trying to implement an event handler for my user control that triggers a click whenever any control inside the user control or the user control itself is clicked.

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);
}

I modified the code given here to bind all the nested controls. This is how I am binding the event on which this user control is used:

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

But the click is not firing on clicking any of the controls inside the user control or the user control itself.

Aishwarya Shiva
  • 3,460
  • 15
  • 58
  • 107

1 Answers1

0

Okay I figured out another way of doing this:

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();
        });
    }
}

Now we can use CardClickAction property on the forms that use this user control like this:

Card1.CardClickAction = new Action(() =>
{
    //your code to execute when user control is clicked
});
Aishwarya Shiva
  • 3,460
  • 15
  • 58
  • 107