如何更改ComboBox中各个项目的ForeColor? (C#Winforms)

我知道我可以像这样改变ComboBox的ForeColor:

comboBox1.ForeColor = Color.Red;

但这会使所有颜色的项目。 当您下拉ComboBox时,每个项目都是红色的。

我想单独着色项目,以便第一项始终为黑色,第二项始终为红色,第三项始终为蓝色,等等。 这可能吗?

另外,我认为我不能为此创建UserControl,因为我使用的ComboBox是Toolstrips的。

您可以使用DrawItem事件 。

此事件由所有者绘制的ComboBox使用。 您可以使用此事件来执行在ComboBox中绘制项目所需的任务。 如果您有一个可变大小的项(当DrawMode属性设置为DrawMode.OwnerDrawVariable时),则在绘制项之前,将引发MeasureItem事件。 您可以为MeasureItem事件创建事件处理程序,以指定要在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(); } 

编辑:刚刚找到一个类似的线程 。

对于ToolStripComboBox派生自ToolStripControlHost。

 //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添加一个事件处理程序到c。