使用不可选择的项目创建 WinForms ComboBox [英] Create WinForms ComboBox with non-selectable items

查看:11
本文介绍了使用不可选择的项目创建 WinForms ComboBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于使用不可选择的项目创建 WinForms ComboBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆