我的用户控件中有不同的控件。并在我的表单中动态加载用户控件
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/