我想从组合框中为所有“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工作。
答案 0 :(得分:1)
您需要将ComboBoxItem上的foreground属性设置为您需要的颜色。
new ComboBoxItem() { Selectable = false, Text="Unselectable", Value=3, Foreground = Brushes.Red},
答案 1 :(得分:0)
您需要将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"
并不好。由于您已拥有属性Selectable
,因此应该真正阅读!cbi.Selectable"
。当然,您必须确保该属性与文本同步。