开发者

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

开发者 https://www.devze.com 2022-12-30 17:00 出处:网络
Using 开发者_JAVA百科C# Winforms (3.5). Is it possible to set the row colors to automatically alternate in a listview?

Using 开发者_JAVA百科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;
}


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.


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


As far as I know WPF allows to set style on any control using <Styles/> But in winforms I'm afraid may be that's the only way.


        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:

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


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消