我想在应用程序中使用 CheckedListBox,其中 ListBox 中的每个项目都是我硬盘驱动器上文件夹的名称,并且为了在这些文件夹中的每一个之间读取和写入文本文件,我想确保只有一个可以在 CheckedListBox 中随时选择一项(文件夹)
如何通过 C# 中的代码实现这一点?
谢谢阅读 :-)
编辑\更新 - 22/10/2010
感谢所有花时间回复的人 - 特别是 Adrift,其更新后的代码运行良好。
我确实很欣赏一些评论员对我以这种方式使用 checklistbox 的评论,但是我觉得它完全符合我的目的,因为我希望毫无疑问地从哪里读取和写入文本文件。
祝一切顺利。
最佳答案
我同意这样的评论,即当只有一个项目被“选中”时,单选按钮将是通常的 UI 元素,但如果你想为你的 UI 坚持使用 CheckedListBox
,你可以尝试这样的事情:
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
CheckedListBox.CheckedIndexCollection checkedIndices = checkedListBox1.CheckedIndices;
if (checkedIndices.Count > 0 && checkedIndices[0] != e.Index)
{
checkedListBox1.SetItemChecked(checkedIndices[0], false);
}
}
您可能还想将
CheckOnClick
设置为 true
的 CheckedListBox
。编辑
根据您的评论更新代码以取消选择未选中的项目。问题是取消选中先前选中的项目会导致事件再次触发。我不知道是否有标准的方法来处理这个问题,但在下面的代码中,我在调用
SetItemCheck
之前分离处理程序,然后重新附加处理程序。这似乎是处理这个问题的一种干净的方法,而且它有效。如果我发现有推荐的方法来处理这个问题,我会更新我的答案。HTH
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
CheckedListBox.CheckedIndexCollection checkedIndices = checkedListBox1.CheckedIndices;
if (checkedIndices.Count > 0)
{
if (checkedIndices[0] != e.Index)
{
// the checked item is not the one being clicked, so we need to uncheck it.
// this will cause the ItemCheck event to fire again, so we detach the handler,
// uncheck it, and reattach the handler
checkedListBox1.ItemCheck -= checkedListBox1_ItemCheck;
checkedListBox1.SetItemChecked(checkedIndices[0], false);
checkedListBox1.ItemCheck += checkedListBox1_ItemCheck;
}
else
{
// the user is unchecking the currently checked item, so deselect it
checkedListBox1.SetSelected(e.Index, false);
}
}
}
关于c# - CheckedListBox - 如何以编程方式确保在任何给定时间只能检查一个项目?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3982482/