如何着色combobox的特定项目

我想从combobox中为所有“Unselectable”文本着色。 我怎样才能做到这一点? 我尝试过,但我无法做到这一点。

我的代码如下:

private class ComboBoxItem { public int Value { get; set; } public string Text { get; set; } public bool Selectable { get; set; } } private void Form1_Load(object sender, EventArgs e) { this.comboBox1.ValueMember = "Value"; this.comboBox1.DisplayMember = "Text"; this.comboBox1.Items.AddRange(new[] { new ComboBoxItem() { Selectable = true, Text="Selectable0", 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 = false, Text="Unselectable", 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#.NET工作。

您需要将ComboBoxItem上的foreground属性设置为您需要的颜色。

 new ComboBoxItem() { Selectable = false, Text="Unselectable", Value=3, Foreground = Brushes.Red}, 

MSDN页面

您需要将ComboBox.DrawMode设置为OwnerDrawxxx并编写DrawItem事件的脚本,例如:

  private void comboBox1_DrawItem(object sender, DrawItemEventArgs e) { e.DrawBackground(); // skip without valid index if (e.Index >= 0) { ComboBoxItem cbi = (ComboBoxItem)comboBox1.Items[e.Index]; Graphics g = e.Graphics; Brush brush = new SolidBrush(e.BackColor); Brush tBrush = new SolidBrush(cbi.Text == "Unselectable" ? Color.Red : e.ForeColor); g.FillRectangle(brush, e.Bounds); e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), e.Font, tBrush, e.Bounds, StringFormat.GenericDefault); brush.Dispose(); tBrush.Dispose(); } e.DrawFocusRectangle(); } 

显然,这部分cbi.Text == "Unselectable"并不好。 由于你已经拥有了一个Property Selectable它应该真正读取!cbi.Selectable" 。当然你必须确保该属性与文本同步。