2008-09-18 17 views

Respuesta

50

Probablemente la única manera de lograr eso es dibujar los elementos usted mismo.

Ajuste el DrawMode a OwnerDrawFixed

y el código de algo como esto en el caso DrawItem:

private void listBox_DrawItem(object sender, DrawItemEventArgs e) 
{ 
    e.DrawBackground(); 
    Graphics g = e.Graphics; 

    g.FillRectangle(new SolidBrush(Color.Silver), e.Bounds); 

    // Print text 

    e.DrawFocusRectangle(); 
} 

La segunda opción sería utilizar un ListView, aunque tienen otro modo de implementaciones (no realmente los datos encuadernado, pero más flexible en forma de columnas)

2
// Set the background to a predefined colour 
MyListBox.BackColor = Color.Red; 
// OR: Set parts of a color. 
MyListBox.BackColor.R = 255; 
MyListBox.BackColor.G = 0; 
MyListBox.BackColor.B = 0; 

Si lo que quiere decir mediante el establecimiento de múltiples backgroun colores d está fijando un color de fondo diferente para cada elemento, esto no es posible con un cuadro de lista, pero es con un ListView, con algo como:

// Set the background of the first item in the list 
MyListView.Items[0].BackColor = Color.Red; 
+2

Es posible con un ListBox. Consulte http://stackoverflow.com/questions/91747/background-color-of-a-listbox-item-winforms#91758 – jfs

+0

s/possible/easy /. Oh bien. C# 1, novato 0. No he trabajado mucho con la sobrecarga de los métodos de pintura. –

+0

el BackColor no es una propiedad de la opción 'ListBox.ObjectCollection' – ghiboz

52

Gracias por la answer by Grad van Horck, que me guió en la dirección correcta .

para que admita texto (no sólo el color de fondo) aquí está mi código totalmente funcional:

//global brushes with ordinary/selected colors 
private SolidBrush reportsForegroundBrushSelected = new SolidBrush(Color.White); 
private SolidBrush reportsForegroundBrush = new SolidBrush(Color.Black); 
private SolidBrush reportsBackgroundBrushSelected = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight)); 
private SolidBrush reportsBackgroundBrush1 = new SolidBrush(Color.White); 
private SolidBrush reportsBackgroundBrush2 = new SolidBrush(Color.Gray); 

//custom method to draw the items, don't forget to set DrawMode of the ListBox to OwnerDrawFixed 
private void lbReports_DrawItem(object sender, DrawItemEventArgs e) 
{ 
    e.DrawBackground(); 
    bool selected = ((e.State & DrawItemState.Selected) == DrawItemState.Selected); 

    int index = e.Index; 
    if (index >= 0 && index < lbReports.Items.Count) 
    { 
     string text = lbReports.Items[index].ToString(); 
     Graphics g = e.Graphics; 

     //background: 
     SolidBrush backgroundBrush; 
     if (selected) 
      backgroundBrush = reportsBackgroundBrushSelected; 
     else if ((index % 2) == 0) 
      backgroundBrush = reportsBackgroundBrush1; 
     else 
      backgroundBrush = reportsBackgroundBrush2; 
     g.FillRectangle(backgroundBrush, e.Bounds); 

     //text: 
     SolidBrush foregroundBrush = (selected) ? reportsForegroundBrushSelected : reportsForegroundBrush; 
     g.DrawString(text, e.Font, foregroundBrush, lbReports.GetItemRectangle(index).Location); 
    } 

    e.DrawFocusRectangle(); 
} 

Lo anterior se suma al código dado y mostrará el texto propiamente dicho, más destacado elemento seleccionado.

+1

Excelente, el bit seleccionado fue muy útil. – Almo

+0

¿Qué son reportsForegroundBrushSelected: reportsForegroundBrush ?? –

+0

reportsForegroundBrushSelected: reportsForegroundBrush me da error, se supone que deben ser declarados, pero ¿cómo? –

0
 public Picker() 
    { 
     InitializeComponent(); 
     this.listBox.DrawMode = DrawMode.OwnerDrawVariable; 
     this.listBox.MeasureItem += listBoxMetals_MeasureItem; 
     this.listBox.DrawItem += listBoxMetals_DrawItem; 
    } 

    void listBoxMetals_DrawItem(object sender, DrawItemEventArgs e) 
    { 
     e.DrawBackground(); 
     Brush myBrush = Brushes.Black; 
     var item = listBox.Items[e.Index] as Mapping; 
     if (e.Index % 2 == 0) 
     { 
      e.Graphics.FillRectangle(new SolidBrush(Color.GhostWhite), e.Bounds); 
     } 
     e.Graphics.DrawString(item.Name, 
      e.Font, myBrush, e.Bounds, StringFormat.GenericDefault); 
     e.DrawFocusRectangle(); 
    } 

muestra completa

0
private void listbox1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e) 
     { 
      e.DrawBackground(); 
      Brush myBrush = Brushes.Black; 
       var item = listbox1.Items[e.Index]; 
       if(e.Index % 2 == 0) 
       { 
        e.Graphics.FillRectangle(new SolidBrush(Color.Gold), e.Bounds); 
       } 


      e.Graphics.DrawString(((ListBox)sender).Items[e.Index].ToString(), 
       e.Font, myBrush,e.Bounds,StringFormat.GenericDefault); 
      e.DrawFocusRectangle(); 
     } 


public MainForm() 
     { 
      InitializeComponent(); 
      this.listbox1.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.listbox1_DrawItem); 
     } 
Cuestiones relacionadas