gpt4 book ai didi

c# - 单击子控件时如何处理控件上的 Click 事件?

转载 作者:行者123 更新时间:2023-11-30 12:27:12 24 4
gpt4 key购买 nike

我有一个包含其他控件的 UserControl:

enter image description here

我需要启用单击用户控件的任何项目,以便我可以设置 UserControl 边框样式。

如果我没有添加任何控件,这会起作用,但是如果我有一个面板,并且我尝试单击该面板,我的 UserControl 的单击事件不会被触发。

这是我的代码:

public partial class TestControl : UserControl
{

public TestControl()
{
InitializeComponent();
this.Click += Item_Click;
IsSelected = false;
}

public bool IsSelected { get; set; }

void Item_Click(object sender, EventArgs e)
{
if (!IsSelected)
{
IsSelected = true;
this.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
}
else
{
IsSelected = false;
this.BorderStyle = System.Windows.Forms.BorderStyle.None;
}
}
}

关于如何触发我的 UserControl 点击事件的任何线索,即使我点击了其他元素?

最佳答案

实际上,实现这一点非常简单,您可以遍历 UserControl 中包含的所有控件,并将 Item_Click 注册到它们的 EventHandler,后者将在触发 Click 事件时调用它:

public partial class TestControl : UserControl {
public TestControl( ) {
//...

for ( int i = 0; i < Controls.Count; i++ ) {
Controls[ i ].Click += Item_Click;
}
}

//...
}

关于c# - 单击子控件时如何处理控件上的 Click 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26105407/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com