在comboBox中,实现自定义加载项需要设定以下俩个内容。
1,comboBox1.DrawMode=OwerDrawFixed; //即设定组合框的加载方式为手动加载。
2,重写comboBox的Draw_Item事件。
private void Form1_Load(object sender, EventArgs e)
{
Array allColors = Enum.GetValues(typeof(KnownColor)); //获得系统颜色集合
foreach (KnownColor var in allColors) //KnownColor是一种枚举类型,包括了系统的所有颜色
{
myComboBox.Items.Add(var.ToString()); //加载该选项框的子项
}
}
private void myComboBox_DrawItem(object sender, DrawItemEventArgs e)
{
//判断是否需要重绘
if (e.Index >= 0)
{
string colorName = myComboBox.Items[e.Index].ToString(); //子项的颜色名
SolidBrush brush = new SolidBrush(Color.FromName(colorName)); //画笔
Font font = new Font("宋体", 9); //字体样式
Rectangle rect = e.Bounds; //获得需要重绘的区域
rect.Inflate(-2, -2); Rectangle rectColor = new Rectangle(rect.Location,new Size(20,rect.Height));
e.Graphics.FillRectangle(brush, rectColor); // 填充颜色
e.Graphics.DrawRectangle(Pens.Black, rectColor); // 绘制边框 //绘制文字
e.Graphics.DrawString(colorName, font, brushs, (rect.X+22), rect.Y);

//绘制选中效果
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
{
SolidBrush brushItem = new SolidBrush(SystemColors.MenuHighlight); //画笔
Rectangle rectItem = e.Bounds;
e.Graphics.FillRectangle(brushItem, rectItem);
}
else
{
SolidBrush brushItem = new SolidBrush(SystemColors.Window); //画笔
Rectangle rectItem = e.Bounds;
e.Graphics.FillRectangle(brushItem, rectItem);