C# 如何为组合框的特定项着色
我想给组合框中的所有“不可选择的”文本上色。我该怎么做?我试过了,但做不到 我的代码如下:C# 如何为组合框的特定项着色,c#,.net,winforms,combobox,C#,.net,Winforms,Combobox,我想给组合框中的所有“不可选择的”文本上色。我该怎么做?我试过了,但做不到 我的代码如下: 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) { t
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上的前台属性设置为所需的颜色
new ComboBoxItem() { Selectable = false, Text="Unselectable", Value=3, Foreground = Brushes.Red},
您需要将
组合框.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.Selective“
。当然,您必须确保属性与文本同步。我尝试过,但没有。在代码中没有任何地方更改项目的颜色。您所做的只是将所选索引设置为-1(无项目)当一个不可选择的项目被选中时。我猜他希望一些自动的东西。你在哪里更改文本或bool可选属性?如果它可以动态工作,这将是一个寻找的地方。你解决了你的问题吗?尽管名称ComboBoxItem
,但这是Winforms
,他的自定义类有nWPF的ComboBoxItem
功能之一。