2014-09-02 89 views

回答

0

这是一个简单的例子。在这个例子中,我的组合框有一些与颜色名称相同的项目(红色,蓝色等),并从中更改每个项目的背景。只要流程中的步骤:

1)设置DrawModeOwnerDrawVariable

如果该属性设置为正常这种控制不会抛出DRAWITEM事件

ComboBox1.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable; 


2)添加DrawItem事件:

ComboBox1.DrawItem += new DrawItemEventHandler(ComboBox1_DrawItem); 


3)输入自己的代码来定义每个项目:

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)颜色需要添加以及:

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"); 

您可以更改矩形大小和位置来绘制您自己的项目,只要你想。
我希望这篇文章很有用。