2014-09-02 93 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"); 

您可以更改矩形大小和位置來繪製您自己的項目,只要你想。
我希望這篇文章很有用。