简体   繁体   中英

Winforms - How to alternate the color of rows in a ListView control?

Using C# Winforms (3.5).

Is it possible to set the row colors to automatically alternate in a listview?

Or do I need to manually set the row color each time a new row is added to the listview?

Based on a MSDN article the manual method would look like this:

//alternate row color
if (i % 2 == 0)
{
    lvi.BackColor = Color.LightBlue;
}
else
{
    lvi.BackColor = Color.Beige;
}

I'm afraid that is the only way in Winforms. XAML allows this through use of styles though.

Set the ListView OwnerDraw property to true and then implement the DrawItem handler :

    private void listView_DrawItem(object sender, DrawListViewItemEventArgs e)
    {
        e.DrawDefault = true;
        if ((e.ItemIndex%2) == 1)
        {
            e.Item.BackColor = Color.FromArgb(230, 230, 255);
            e.Item.UseItemStyleForSubItems = true;
        }
    }

    private void listView_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
    {
        e.DrawDefault = true;
    }

This example is a simple one, you can improve it.

据我所知,WPF允许使用<Styles/>在任何控件上设置样式但是在winforms中我担心这可能是唯一的方法。

Set the ListView OwnerDraw property to true and then implement the DrawItem handler. Have a look here : Winforms - How to alternate the color of rows in a ListView control?

        for (int i = 0; i <= listView.Items.Count - 1; i = (i + 2))
        {
            listView.Items[i].BackColor = Color.Gainsboro;
        }

Set the main background in the properties menu then use this code to set the alternate color.

You can also take advantage of owner drawing, rather than setting properties explicitly. Owner drawing is less vulnerable to item reordering.

Here is how to do this in Better ListView (a 3rd party component offering both free and extended versions) - its a matter of simply handling a DrawItemBackground event:

private void ListViewOnDrawItemBackground(object sender, BetterListViewDrawItemBackgroundEventArgs eventArgs)
{
    if ((eventArgs.Item.Index & 1) == 1)
    {
        eventArgs.Graphics.FillRectangle(Brushes.AliceBlue, eventArgs.ItemBounds.BoundsOuter);
    }
}

result:

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM