如何使用不可选择的项目创建组合框控件?例如,这样的组名或类别名在视觉上将下拉列表中的项目划分为一些组或类别。
最佳答案
您可以添加一个特殊的类并使用所选项目来确定该项目是否被选中,而不是向您的组合框添加字符串。
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/