문제

System.Windows.Forms.ListBox에서 특정 항목의 배경색을 어떻게 설정합니까?가능하다면 여러개를 설정할 수 있었으면 좋겠습니다.

도움이 되었습니까?

해결책

아마도 이를 달성하는 유일한 방법은 항목을 직접 그리는 것입니다.

설정 DrawMode 에게 OwnerDrawFixed

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

두 번째 옵션은 다른 구현 방법이 있지만 ListView를 사용하는 것입니다(실제로 데이터 바인딩은 아니지만 열 방식이 더 유연함).

다른 팁

감사합니다 Grad van Horck의 답변, 그것은 나를 올바른 방향으로 안내했습니다.

배경색뿐만 아니라 텍스트를 지원하기 위해 완전히 작동하는 코드는 다음과 같습니다.

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

위 코드는 주어진 코드에 추가되며 적절한 텍스트와 선택한 항목을 강조 표시합니다.

// 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;

여러 배경색을 설정한다는 것이 각 항목에 대해 서로 다른 배경색을 설정한다는 의미라면 ListBox에서는 불가능하지만 ListView에서는 다음과 같습니다.

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

완전한 샘플

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top