c# - 单击动态用户控件中的控件时未触发单击事件

标签 c# winforms event-handling click dynamic-usercontrols

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

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
}

当我在用户控件中单击控件时,单击事件没有触发。它仅在我单击用户控件的空白区域时触发。

最佳答案

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

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

}

关于c# - 单击动态用户控件中的控件时未触发单击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16940270/

相关文章:

winforms - 是否可以避免 Winform 上的多次按钮点击?

c# - 无法使用 pinvoke 将 WM_CLOSE 发送到 Windows 资源管理器窗口

c# - 为 PDF 设置页边距、页眉和页脚而不重叠

.net - XML反序列化回车导致无法打印字符

c# - 无法使用程序,因为文件已在使用中

c# - 检测窗体何时关闭 C#

c# - Web API 获取多部分/表单数据响应的最简单方法

c# - 对话框确认 Jquery Ui : Calling a VB or C# method

c# - 在窗体之间传递对象 C#

c# - 带有事件处理程序的 asp.net 动态按钮