CheckedListBox控件 – 仅在单击实际复选框时选中复选框

我在我正在使用的小应用程序中使用CheckedListBox控件。 这是一个很好的控制,但有一件事困扰我; 我无法设置属性,以便它只在我实际选中复选框时检查项目。 克服这个问题的最佳方法是什么? 我一直在考虑从复选框的左侧获取鼠标点击的位置。 这部分工作,但如果我点击一个空的空间,左边足够靠近,仍然会检查当前所选项目。 关于这个的任何想法?

嗯,这很难看,但你可以通过挂钩CheckedListBox.MouseDownCheckedListBox.ItemCheck来计算项目矩形的鼠标点击坐标,如下所示

 ///  /// In order to control itemcheck changes (blinds double clicking, among other things) ///  bool AuthorizeCheck { get; set; } private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) { if(!AuthorizeCheck) e.NewValue = e.CurrentValue; //check state change was not through authorized actions } private void checkedListBox1_MouseDown(object sender, MouseEventArgs e) { Point loc = this.checkedListBox1.PointToClient(Cursor.Position); for (int i = 0; i < this.checkedListBox1.Items.Count; i++) { Rectangle rec = this.checkedListBox1.GetItemRectangle(i); rec.Width = 16; //checkbox itself has a default width of about 16 pixels if (rec.Contains(loc)) { AuthorizeCheck = true; bool newValue = !this.checkedListBox1.GetItemChecked(i); this.checkedListBox1.SetItemChecked(i, newValue);//check AuthorizeCheck = false; return; } } } 

我知道这个post有点旧,但我不认为提供另一个解决方案是个问题:

 private void checkedListBox1_MouseClick(object sender, MouseEventArgs e) { if ((e.Button == MouseButtons.Left) & (eX > 13)) { this.checkedListBox1.SetItemChecked(this.checkedListBox1.SelectedIndex, !this.checkedListBox1.GetItemChecked(this.checkedListBox1.SelectedIndex)); } } 

CheckOnClick = True的值)。

你可以在矩形中使用那个东西,但为什么要使它变得更加复杂。

另一种解决方案是简单地使用Treeview。
将CheckBoxes设置为true,将ShowLines设置为false,将ShowPlusMinus设置为false,并且您与CheckedListBox基本相同。 只有在单击实际的CheckBox时才会检查这些项目。

CheckedListBox更简单,但TreeView提供了许多可能更适合您的程序的选项。

默认情况下,CheckedListBox中复选框的文本是在复选框输入后放置HTML标签,并将标签的“for”属性设置为复选框的ID。

当标签表示它是“for”的元素时,单击该标签会告诉浏览器关注该元素,这就是您所看到的。

有两个选项是使用单独的CheckBox控件和文本(不是CheckBox的Text属性,因为它与CheckBoxList做同样的事情)呈现您自己的列表,如果列表是静态的,或者如果列表是,则使用类似Repeater的内容动态。

试试这个。 将iLastIndexClicked声明为表单级int变量。

 private void chklst_MouseClick(object sender, MouseEventArgs e) { Point p = chklst.PointToClient(MousePosition); int i = chklst.IndexFromPoint(p); if (pX > 15) { return; } // Body click. if (chklst.CheckedIndices.Contains(i)){ return; } // If already has focus click anywhere works right. if (iLastIndexClicked == i) { return; } // native code will check/uncheck chklst.SetItemChecked(i, true); iLastIndexClicked = i; } 

只需检查用户是否点击了选中列表的最左侧15个像素(复选框区域),除了重新检查当前选定的项目外,它始终有效。 存储最后一个索引并退出而不进行更改会使本机代码正确处理,尝试将其设置为已检查,在这种情况下将其打开并在“ItemCheck”代码运行时关闭。