问题
I want to customize my combobox each item, same as font, background, etc.
Is there any simple way to set custom background color of each Combobox item?
回答1:
This is simple example to do that. In this example my combobox has some item same as color name (Red, Blue, etc) and change the background of each item from this. Just flow the steps:
1) Set the DrawMode to OwnerDrawVariable:
If this property set to Normal this control never raise DrawItem event
ComboBox1.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
2) Add an DrawItem event:
ComboBox1.DrawItem += new DrawItemEventHandler(ComboBox1_DrawItem);
3) Entry your own code to customize each item:
private void ComboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
Graphics g = e.Graphics;
Rectangle rect = e.Bounds; //Rectangle of item
if (e.Index >= 0)
{
//Get item color name
string itemName = ((ComboBox)sender).Items[e.Index].ToString();
//Get instance a font to draw item name with this style
Font itemFont = new Font("Arial", 9, FontStyle.Regular);
//Get instance color from item name
Color itemColor = Color.FromName(itemName);
//Get instance brush with Solid style to draw background
Brush brush = new SolidBrush(itemColor);
//Draw the item name
g.DrawString(itemName, itemFont, Brushes.Black, rect.X, rect.Top);
//Draw the background with my brush style and rectangle of item
g.FillRectangle(brush, rect.X, rect.Y, rect.Width, rect.Height);
}
}
4) Colors need to be added as well:
ComboBox1.Items.Add("Black");
ComboBox1.Items.Add("Blue");
ComboBox1.Items.Add("Lime");
ComboBox1.Items.Add("Cyan");
ComboBox1.Items.Add("Red");
ComboBox1.Items.Add("Fuchsia");
ComboBox1.Items.Add("Yellow");
ComboBox1.Items.Add("White");
ComboBox1.Items.Add("Navy");
ComboBox1.Items.Add("Green");
ComboBox1.Items.Add("Teal");
ComboBox1.Items.Add("Maroon");
ComboBox1.Items.Add("Purple");
ComboBox1.Items.Add("Olive");
ComboBox1.Items.Add("Gray");
You can change the rectangle size and position to draw your own item as you want.
I hope this post is useful.
来源:https://stackoverflow.com/questions/25616697/color-picker-combo-box