开发者

Varying ListViews item background color

How can I make it so that a ListViews control's ba开发者_StackOverflowckground color for items varies from item to item like in WinAmp, along with changing the column header colors?

Varying ListViews item background color

If you look closely you can see the first item is a dark gray and the second is black and so on.


You can set the ListViewItem.BackColor property, however this has to be done manually for each alternating line. Alternatively you could use a DataGridView which has an AlternateRowStyle property that would do this automatically - albeit you'll need to databind your rows in a collection of sorts which is a whole other topic.

For the simple case:

foreach (ListViewItem item in listView1.Items)
{
    item.BackColor = item.Index % 2 == 0 ? Color.Red : Color.Black;
}


Handle the DrawItem event on the listbox and set the DrawMode to OwnerDrawVariable. The DrawItemEventArgs provides a BackColor property that can be set based on the index (also in the arg).


I take it that you add rows (subitems) in a loop? If so use a loop counter to figure out which colour you want.

string[] strings = new string[]{"dild", "dingo"};
int i = 0;
foreach (var item in strings)
{
    Color color = i++ % 2 == 0 ? Color.LightBlue :  Color.LightCyan;
    ListViewItem lv = listView1.Items.Add(item);
    lv.SubItems[0].BackColor = color;
}


private static void RepaintListView(ListView lw)
{
    var colored = false;
    foreach (ListViewItem item in lw.Items)
    {
        item.BackColor = colored ? Color.LightBlue : Color.White;
        colored = !colored;
    }
}

You can call this method after item addition. Or use it directly on add


for (int index = 0; index <= ListView1.Items.Count; index++) 
{
    if (index % 2 == 0) 
    {
        ListView1.Items(index).BackColor = Color.LightGray;
    }

}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜