我知道我可以像这样改变ComboBox的ForeColor:
comboBox1.ForeColor = Color.Red;
但这会使所有颜色的项目。当您下拉ComboBox时,每个项目都是红色的。
我想单独为项目着色,以便第一项始终黑色,第二项始终红色,第三项始终蓝色,等等等等。这可能吗?
此外,我不认为我可以为此创建UserControl,因为我使用的ComboBox是Toolstrips的一个。
答案 0 :(得分:2)
您可以使用DrawItem event。
此事件由所有者绘制的ComboBox使用。您可以使用此活动 执行在ComboBox中绘制项目所需的任务。如果你有 一个可变大小的项(当DrawMode属性设置为 DrawMode.OwnerDrawVariable),在绘制项目之前,MeasureItem 事件被提出。您可以为MeasureItem创建事件处理程序 event指定要绘制的项目的大小 DrawItem事件的事件处理程序。
MSDN示例:
// You must handle the DrawItem event for owner-drawn combo boxes.
// This event handler changes the color, size and font of an
// item based on its position in the array.
protected void ComboBox1_DrawItem(object sender,
System.Windows.Forms.DrawItemEventArgs e)
{
float size = 0;
System.Drawing.Font myFont;
FontFamily family = null;
System.Drawing.Color animalColor = new System.Drawing.Color();
switch(e.Index)
{
case 0:
size = 30;
animalColor = System.Drawing.Color.Gray;
family = FontFamily.GenericSansSerif;
break;
case 1:
size = 10;
animalColor = System.Drawing.Color.LawnGreen;
family = FontFamily.GenericMonospace;
break;
case 2:
size = 15;
animalColor = System.Drawing.Color.Tan;
family = FontFamily.GenericSansSerif;
break;
}
// Draw the background of the item.
e.DrawBackground();
// Create a square filled with the animals color. Vary the size
// of the rectangle based on the length of the animals name.
Rectangle rectangle = new Rectangle(2, e.Bounds.Top+2,
e.Bounds.Height, e.Bounds.Height-4);
e.Graphics.FillRectangle(new SolidBrush(animalColor), rectangle);
// Draw each string in the array, using a different size, color,
// and font for each item.
myFont = new Font(family, size, FontStyle.Bold);
e.Graphics.DrawString(animals[e.Index], myFont, System.Drawing.Brushes.Black, new RectangleF(e.Bounds.X+rectangle.Width, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height));
// Draw the focus rectangle if the mouse hovers over an item.
e.DrawFocusRectangle();
}
编辑: 刚刚找到similar thread。
答案 1 :(得分:1)
对于从ToolStripControlHost派生的ToolStripComboBox。
//Declare a class that inherits from ToolStripControlHost.
public class ToolStripCustomCombo : ToolStripControlHost
{
// Call the base constructor passing in a MonthCalendar instance.
public ToolStripCustomCombo() : base(new ComboBox()) { }
public ComboBox ComboBox
{
get
{
return Control as ComboBox;
}
}
}
然后说你有一个名为m_tsMain的工具条。以下是添加新控件的方法。
ToolStripCustomCombo customCombo = new ToolStripCustomCombo();
ComboBox c = customCombo.ComboBox;
c.Items.Add("Hello World!!!");
c.Items.Add("Goodbye cruel world!!!");
m_tsMain.Items.Add(customCombo);
你应该能够为DrawItem添加一个事件处理程序。