WinForms ListBox带有只读/禁用项 [英] WinForms ListBox with readonly/disabled items

查看:139
本文介绍了WinForms ListBox带有只读/禁用项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以使ListBox中的某些项目变为只读/禁用状态,从而使其无法选择?还是有类似ListBox的控件来提供此功能?

Is there a way to make some of the items in a ListBox readonly/disabled so they can't be selected? Or are there any similar controls to ListBox to provide this functionality?

推荐答案

ListBox不支持该功能.您可以用螺栓固定一些东西,也可以取消选择一个选定的项目.这是一个愚蠢的示例,可防止选择偶数编号的项目:

ListBox doesn't have support for that. You can bolt something on, you could deselect a selected item. Here's a silly example that prevents even-numbered items from being selected:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e) {
  for (int ix = listBox1.SelectedIndices.Count - 1; ix >= 0; ix--) {
    if (listBox1.SelectedIndices[ix] % 2 != 0) 
      listBox1.SelectedIndices.Remove(listBox1.SelectedIndices[ix]);
  }
}

但是闪烁非常明显,并且弄乱了键盘导航.使用CheckedListBox可以获得更好的结果,可以防止用户选中某项的框:

But the flicker is quite noticeable and it messes up keyboard navigation. You can get better results by using CheckedListBox, you can prevent the user from checking the box for an item:

private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) {
  if (e.Index % 2 != 0) e.NewValue = CheckState.Unchecked;
}

但是现在您不能替代图形以使它对用户来说很明显,该项目是不可选择的.这里没有很好的解决方案,只在不应该选择的框中显示项目要简单得多.

But now you cannot override drawing to make it look obvious to the user that the item isn't selectable. No great solutions here, it is far simpler to just not display items in the box that shouldn't be selectable.

这篇关于WinForms ListBox带有只读/禁用项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆