How to Color particular item of combobox

后端 未结 2 1055
小鲜肉
小鲜肉 2021-01-25 20:50

I want to color all \"Unselectable\" Text from combo box. How can i do this? I tried it but i am unable to do this.

My Code is Given Below:



        
2条回答
  •  半阙折子戏
    2021-01-25 21:33

    You need to set the ComboBox.DrawMode to OwnerDrawxxx and script the DrawItem event e.g. like this:

     private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
     {
    
        e.DrawBackground();
         // skip without valid index
        if (e.Index >= 0) 
        {
          ComboBoxItem cbi = (ComboBoxItem)comboBox1.Items[e.Index];
          Graphics g = e.Graphics;
          Brush brush =  new SolidBrush(e.BackColor);
          Brush tBrush = new SolidBrush(cbi.Text == "Unselectable" ? Color.Red : e.ForeColor);
    
          g.FillRectangle(brush, e.Bounds);
          e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), e.Font,
                     tBrush, e.Bounds, StringFormat.GenericDefault);
          brush.Dispose();
          tBrush.Dispose();
        }
        e.DrawFocusRectangle();
    
     }
    

    This part cbi.Text == "Unselectable"is not good, obviously. Since you already have a Property Selectable it should really read !cbi.Selectable". Off course you must make sure that the property is in synch with the text.

提交回复
热议问题