I have a class that populates a ListView by passing a list of objects. The class uses reflection to see the properties of each object in order to generate the ListView. How could I change the background color of a row in the ListView.
This page does exactly what I am looking for. The only problem is that my ListView is bound to the list of objects. In other words each item of the ListView is an object that is bound instead of a ListViewItem. I am assuming that is the reason why I cannot cast some item in the ListView to a ListViewItem. For example when I do this:
ListViewItem someItem = (ListViewItem)listView1.Items[0];
I get an InvalidcastException because if I where to physically add the objects to the ListView like:
listview.items.add(someObject) then this will work, but because I am binding the list to the ListView that line does not work. I think that is the reason why I am not able to cast. The reason why I want to cast it is becasue a ListViewItem has a Background property.
EDIT
I am able to do that with the first 12 objects I have tried the folowing:
for (int i = 0; i < listView1.Items.Count; i++)
{
var lvitem = listView1.ItemContainerGenerator.ContainerFromIndex(i) as ListViewItem;
lvitem.Foreground = Brushes.Green;
}
and I get this error:
and I also have tried this:
foreach (Tiro t in listView1.Items)
{
var lvitem = listView1.ItemContainerGenerator.ContainerFromItem(t) as ListViewItem;
if (t.numero == 0 || t.numero == 37)
{
//lvitem.Background = Brushes.Green;
lvitem.Foreground = Brushes.Green;
}
else if (t.numero % 2 == 0)
{
//lvitem.Background = Brushes.Red;
lvitem.Foreground = Brushes.Red;
}
else
{
//lvitem.Background = Brushes.Gray;
lvitem.Foreground = Brushes.Black;
}
}
and I get the same error:
I don't understand why lvitem is null after the 12 iteration?
It only works with the items that are being displayed....
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…