项目中多个CheckedListBox需复用单选行为,如何避免重复写事件代码?
实现多CheckListBox复用单选逻辑的两种方案
方案1:通用共享事件处理(快速适用)
把原代码里写死的控件实例替换为从sender参数动态获取的触发事件的CheckListBox实例,所有需要单选功能的CheckListBox都可以绑定同一个事件处理方法,无需重复写逻辑:
private void CommonClb_ItemCheck(object sender, ItemCheckEventArgs e) { // 从sender获取当前触发事件的CheckListBox实例 if (sender is not CheckedListBox clb) return; // 取消其他所有项的选中状态 for (int ix = 0; ix < clb.Items.Count; ++ix) { if (ix != e.Index) { clb.SetItemChecked(ix, false); } } clb.ClearSelected(); // 可选调整:如果需要支持点击已选中项取消选中(允许全不选状态),可以注释上面的逻辑,换成下面的版本 /* if (e.NewValue == CheckState.Checked) { for (int ix = 0; ix < clb.Items.Count; ++ix) { if (ix != e.Index) { clb.SetItemChecked(ix, false); } } } clb.ClearSelected(); */ }
使用方法:选中所有需要单选的CheckListBox,在属性面板的事件页找到ItemCheck事件,选择绑定到上面的CommonClb_ItemCheck方法即可。
方案2:封装自定义控件(一劳永逸,适合高频使用场景)
如果项目中大量使用带单选功能的CheckListBox,可以直接封装自定义控件,拖到窗体上自动具备单选能力,无需手动绑定事件:
using System.Windows.Forms; public class SingleCheckListBox : CheckedListBox { protected override void OnItemCheck(ItemCheckEventArgs e) { base.OnItemCheck(e); // 内置单选逻辑 if (e.NewValue == CheckState.Checked) { for (int i = 0; i < Items.Count; i++) { if (i != e.Index) { SetItemChecked(i, false); } } } ClearSelected(); } }
编译项目后,就能在工具箱看到SingleCheckListBox控件,直接拖用即可。
内容的提问来源于stack exchange,提问作者Niklas A
相关产品推荐
相关产品推荐

