Click event is not firing when I click a control in dynamic usercontrol(当我单击动态用户控件中的控件时,单击事件未触发)
问题描述
我的用户控件中有不同的控件.并在我的表单中动态加载用户控件
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);
}
}
这篇关于当我单击动态用户控件中的控件时,单击事件未触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:当我单击动态用户控件中的控件时,单击事件未触发
基础教程推荐
- 如果条件可以为空 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 将数据集转换为列表 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
