当我单击动态用户控件中的控件时,单击事件未触发 [英] Click event is not firing when I click a control in dynamic usercontrol

查看:25
本文介绍了当我单击动态用户控件中的控件时,单击事件未触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的用户控件中有不同的控件.并在我的表单中动态加载用户控件

I have different controls in my usercontrols. And load usercontrols dynamically in my form

UserControl2 usercontrol = new UserControl2();
usercontrol.Tag = i;
usercontrol.Click += usercontrol_Click;
flowLayoutPanel1.Controls.Add(usercontrol);

private void usercontrol_Click(object sender, EventArgs e)
{
   // handle event
}

单击用户控件中的控件时未触发单击事件.只有当我点击用户控件的空白区域时才会触发.

The click event is not firing when I click a control in usercontrol. It only fires when I click on empty area of usercontrol.

推荐答案

递归所有控件并将每个控件的 Click() 事件连接到同一个处理程序.从那里调用 InvokeOnClick().现在点击任何东西都会触发主 UserControl 的 Click() 事件:

Recurse through all the controls and wire up the Click() event of each to the same handler. From there call InvokeOnClick(). Now clicking on anything will fire the Click() event of the main UserControl:

public partial class UserControl2 : UserControl
{

    public UserControl2()
    {
        InitializeComponent();
        WireAllControls(this);
    }

    private void WireAllControls(Control cont)
    {
        foreach (Control ctl in cont.Controls)
        {
            ctl.Click += ctl_Click;
            if (ctl.HasChildren)
            {
                WireAllControls(ctl);
            }
        }
    }

    private void ctl_Click(object sender, EventArgs e)
    {
        this.InvokeOnClick(this, EventArgs.Empty); 
    }

}

这篇关于当我单击动态用户控件中的控件时,单击事件未触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆