Question

Comment définir la couleur d'arrière-plan d'un élément spécifique dans un System.Windows.Forms.ListBox? J'aimerais pouvoir en définir plusieurs si possible.

Était-ce utile?

La solution

Le seul moyen d'y parvenir est probablement de dessiner vous-même les objets.

Définissez le DrawMode sur OwnerDrawFixed

et codez quelque chose comme ceci sur l'événement 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 deuxième option consisterait en un ListView, bien qu’ils aient une autre méthode d’implémentation (pas vraiment liée aux données, mais plus flexible en colonnes)

Autres conseils

Merci pour la réponse de Grad van Horck , qui m'a guidé dans la bonne direction.

Pour prendre en charge le texte (pas seulement la couleur de fond), voici mon code qui fonctionne:

//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();
}

Ce qui précède ajoute au code donné et affichera le texte correct plus l’élément sélectionné en surbrillance.

// 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 vous définissez plusieurs couleurs d'arrière-plan en définissant une couleur d'arrière-plan différente pour chaque élément, ce n'est pas possible avec un ListBox, mais avec un ListView, avec quelque chose comme:

// Set the background of the first item in the list
MyListView.Items[0].BackColor = Color.Red;
public MainForm()
{
    InitializeComponent();
    this.listbox1.DrawItem += new DrawItemEventHandler(this.listbox1_DrawItem);
}

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 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();
}

Échantillon complet

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top