C# 使用不可选择的项目创建 WinForms ComboBox

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2290563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:07:22  来源:igfitidea点击:

Create WinForms ComboBox with non-selectable items

c#.netwinformscombobox

提问by symantis

How to create combobox control with non-selectable items? For example, such groupnames or categorynames which visually divide items in dropdownlist into some groups or categories.

如何使用不可选择的项目创建组合框控件?例如,这样的组名或类别名将下拉列表中的项目直观地划分为一些组或类别。

采纳答案by AxelEckenberger

Instead of adding strings to your combobox you could add a special class and use selected item to determine whether the item is selected or not.

您可以添加一个特殊的类并使用选定的项目来确定是否选择了该项目,而不是向组合框添加字符串。

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;
            }
        };
    }
}

回答by t0mm13b

Have a look here on CodeProjectfor a readonly Combo Box, here's another article to make the readonlycombo box 'decent' looking... Here's another that shows how to override the basic standard combo box to make it readonlyas Sani suggested.

CodeProject 上查看只读组合框,这是另一篇使只读组合框看起来“体面”的文章……这是另一篇文章,展示了如何按照 Sani 的建议覆盖基本标准组合框以使其成为只读