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

后端 未结 6 949
天涯浪人
天涯浪人 2021-01-05 04:33

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

相关标签:
6条回答
  • 2021-01-05 04:48

    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:

    enter image description here

    0 讨论(0)
  • 2021-01-05 04:50

    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.

    0 讨论(0)
  • 2021-01-05 04:53

    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 讨论(0)
  • 2021-01-05 05:00

    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.

    0 讨论(0)
  • 2021-01-05 05:01

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

    0 讨论(0)
  • 2021-01-05 05:05
            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.

    0 讨论(0)
提交回复
热议问题