listbox Items 自定义颜色的实现

private void listBox1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
{
   // Set the DrawMode property to draw fixed sized items.
   listBox1.DrawMode = DrawMode.OwnerDrawFixed;
   // Draw the background of the ListBox control for each item.
   e.DrawBackground();
   // Define the default color of the brush as black.
   Brush myBrush = Brushes.Black;

   // Determine the color of the brush to draw each item based on the index of the item to draw.
   switch (e.Index)
   {
      case 0:
         myBrush = Brushes.Red;
         break;
      case 1:
         myBrush = Brushes.Orange;
         break;
      case 2:
         myBrush = Brushes.Purple;
         break;
   }

   // Draw the current item text based on the current Font and the custom brush settings.
   e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, myBrush,e.Bounds,StringFormat.GenericDefault);
   // If the ListBox has focus, draw a focus rectangle around the selected item.
   e.DrawFocusRectangle();
}

在listbox里面添加DrawItem事件后,添加如上代码,可以实现items变色,但是不能实现选中items后反色的效果,必须加如下代码:

 

     if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
            {
                e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, Brushes.White, e.Bounds, StringFormat.GenericDefault);

            }


 

你可能感兴趣的:(listbox)