Цвет списка переднего плана - PullRequest
0 голосов
/ 01 октября 2010

Итак, у меня есть этот код, чтобы изменить цвет выделения фона элемента списка на красный в Winforms по умолчанию.

if (e.Index < 0) return;
            // if the item state is selected then change the back color 
            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
                e = new DrawItemEventArgs(e.Graphics,
                                          e.Font,
                                          e.Bounds,
                                          e.Index,
                                          e.State ^ DrawItemState.Selected,
                                          e.ForeColor,
                                          Color.Red); // Choose the color

            // Draw the background of the ListBox control for each item.
            e.DrawBackground();
            // Draw the current item text
            e.Graphics.DrawString(studentsListBox.Items[e.Index].ToString(), e.Font, Brushes.Black, e.Bounds, StringFormat.GenericDefault);
            // If the ListBox has focus, draw a focus rectangle around the selected item.
            e.DrawFocusRectangle();

Это отлично работает, но я также хочу изменить цвет шрифта для выбранного элемента,Как мне это сделать?

Ответы [ 2 ]

1 голос
/ 01 октября 2010
if (e.Index < 0)
    return;

Brush foreBrush = Brushes.Black; // non-selected text color
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
{
    foreBrush = Brushes.White; // selected text color
    e = new DrawItemEventArgs(e.Graphics,
                              e.Font,
                              e.Bounds,
                              e.Index,
                              e.State ^ DrawItemState.Selected,
                              e.ForeColor,
                              Color.Red); // Choose the color 
}

// Draw the background of the ListBox control for each item. 
e.DrawBackground();
// Draw the current item text
e.Graphics.DrawString((sender as ListBox).Items[e.Index].ToString(), e.Font, foreBrush, e.Bounds, StringFormat.GenericDefault);
// If the ListBox has focus, draw a focus rectangle around the selected item. 
e.DrawFocusRectangle(); 
0 голосов
/ 01 октября 2010

Разве вы не можете просто указать цвет, отличный от e.ForeColor?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...