title: Change background color of ListView row programmatically (wpf)
body: <p>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. </p>
  
  <p>This <a href="http://www.csharp411.com/add-shaded-rows-to-listview-details-view/" rel="noreferrer">page</a> 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:</p>
  
  <pre><code>ListViewItem someItem = (ListViewItem)listView1.Items[0];
  </code></pre>
  
  <p>I get an InvalidcastException because if I where to physically add the objects to the ListView like:</p>
  
  <p>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. </p>
  
  <p>EDIT</p>
  
  <p>I am able to do that with the first 12 objects I have tried the folowing:</p>
  
  <pre><code>for (int i = 0; i &lt; listView1.Items.Count; i++)
  {
      var lvitem = listView1.ItemContainerGenerator.ContainerFromIndex(i) as ListViewItem;
      lvitem.Foreground = Brushes.Green;                
  }
  </code></pre>
  
  <p>and I get this error:</p>
  
  <p><img src="https://i.stack.imgur.com/k61xu.png" alt="first try"></p>
  
  <p>and I also have tried this:</p>
  
  <pre><code>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;
      }
  
  }
  </code></pre>
  
  <p>and I get the same error:</p>
  
  <p><img src="https://i.stack.imgur.com/UcH6T.png" alt="enter image description here"></p>
  
  <p>I don't understand why lvitem is null after the 12 iteration?</p>
  
  <p>It only works with the items that are being displayed....</p>