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

标签 c# .net winforms combobox

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

最佳答案

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

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

关于c# - 使用不可选择的项目创建 WinForms ComboBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2290563/

相关文章:

c# - ASP.NET MVC Web App 用户登录后,SQL Server Express 无法连接且没有任何有用的错误信息

c# - 解析值 : [ 时遇到意外字符

c# - 数据绑定(bind) Winforms 文本框

c# - .Net 如何为用户控件的属性设置 IsReadOnly

vb.net - 表单位置 VB.net

c# - Silverlight 方法中的异步操作 - 返回值

c# - 创建的动态按钮单击事件 OnPreRender 不会触发

c# - 如何检查给定进程已创建到 Internet 的哪些连接

c# - 将通用集合 List<> 绑定(bind)到属性网格

c# - WinForms Livecharts 图表标题