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

查看:22
本文介绍了带有只读/禁用项目的 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天全站免登陆