简体   繁体   English

使用不可选项创建WinForms ComboBox

[英]Create WinForms ComboBox with non-selectable items

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. 例如,可以将下拉列表中的项目可视地划分为某些组或类别的组名或类别名称。

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

看看CodeProject上的一个只读组合框,这是另一篇文章,让readonly组合框“体面”看......这是另一篇文章,展示了如何覆盖基本标准组合框,使其像Sai建议的那样只读

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM