创建具有不可选项的WinForms ComboBox

10
如何创建带有不可选择项的组合框控件?例如,将组名或类别名用于视觉上将下拉列表中的项目分成一些组或类别。

你可以提供更多细节吗?这是WPF、Windows Forms还是其他UI框架? - mattythomas2000
2个回答

13

您可以添加一个特殊的类,而不是将字符串添加到组合框中,并使用所选项目来确定该项目是否已被选中。

public partial class Form1 : Form
{
    private class ComboBoxItem
    {
        public int Value { get; set; }
        public string Text { get; set; }
        public bool Selectable { get; set; }
    }

    public Form1() {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e) {
        this.comboBox1.ValueMember = "Value";
        this.comboBox1.DisplayMember = "Text";
        this.comboBox1.Items.AddRange(new[] {
            new ComboBoxItem() { Selectable = false, Text="Unselectable", Value=0},
            new ComboBoxItem() { Selectable = true, Text="Selectable1", Value=1},
            new ComboBoxItem() { Selectable = true, Text="Selectable2", Value=2},
            new ComboBoxItem() { Selectable = false, Text="Unselectable", Value=3},
            new ComboBoxItem() { Selectable = true, Text="Selectable3", Value=4},
            new ComboBoxItem() { Selectable = true, Text="Selectable4", Value=5},
        });

        this.comboBox1.SelectedIndexChanged += (cbSender, cbe) => {
            var cb = cbSender as ComboBox;

            if (cb.SelectedItem != null && cb.SelectedItem is ComboBoxItem && ((ComboBoxItem) cb.SelectedItem).Selectable == false) {
                // deselect item
                cb.SelectedIndex = -1;
            }
        };
    }
}

这也是我的第一反应。但是你仍然可以在组合框中输入项目文本,从而选择不可选项目。 - Sani Huttunen
3
不。在我的情况下,我使用DropDownList样式来禁用ComboBox的文本编辑器。 - symantis
你的代码非常好,对我很有帮助。但是还有一个问题 - 如何禁用不仅在列表中选择项目,而且禁用鼠标跟踪不可选择的项目。 - symantis
在我看来,要想不借助于自绘下拉框实现这个功能是很困难的。 - AxelEckenberger
1
这是一个不错的解决方案,但如果出现无法选择的项目,希望能够返回到先前选择的项目,而不是删除任何选择。 - sandwood

0

CodeProject上看一下只读组合框,这里有另一篇文章可以让只读组合框看起来“不错”... 这里还有另一篇文章展示如何重写基本标准组合框,使其像Sani建议的那样只读


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接