title: Metro app - ListView - how to alternate background colour of ListViewItems
body: <p>In my Metro style app for Windows 8, I'm binding a Listview to an ObservableCollection and I would like the background color of each ListViewItem to alternate  (white, gray, white, etc)</p>
  
  <pre><code>   &lt;ListView x:Name="stopsListView" ItemsSource="{Binding}" &gt;
          &lt;ListView.ItemTemplate&gt;
              &lt;DataTemplate&gt;
                  &lt;Grid Height="66" &gt;
                      &lt;TextBlock Text="{Binding Title}" /&gt;
                  &lt;/Grid&gt;
              &lt;/DataTemplate&gt;
          &lt;/ListView.ItemTemplate&gt;
  </code></pre>
  
  <p>In WPF, this is done using a Style with Triggers - see <a href="http://refat38.wordpress.com/2011/03/23/wpf-listview-alternate-row-color/" rel="nofollow noreferrer">this page</a>.  </p>
  
  <p>How do you accomplish this in a Metro app?</p>
  
  <p><strong>Update:</strong></p>
  
  <p>After the correct answer was given below, I went away and actually coded it.  Here's some code for anyone who needs it:</p>
  
  <p>Code for value converter class:</p>
  
  <pre><code>public class AltBackgroundConverter : IValueConverter
  {
      public object Convert(object value, Type targetType, object parameter, string language)
      {
          if (!(value is int)) return null;
          int index = (int)value;
  
          if (index % 2 == 0)
              return Colors.White;
          else
              return Colors.LightGray;
      }
  
      // No need to implement converting back on a one-way binding
      public object ConvertBack(object value, Type targetType, object parameter, string language)
      {
          throw new NotImplementedException();
      }
  }
  </code></pre>
  
  <p>Code for XAML listview:
   
          
              
          </p>
  
  <pre><code>    &lt;ListView x:Name="stopsListView" ItemsSource="{Binding}"&gt;
  
          &lt;ListView.ItemTemplate&gt;
              &lt;DataTemplate&gt;
                  &lt;Grid Width="250" Height="66" Margin="5"&gt;
                      &lt;Grid.Background&gt;
                          &lt;SolidColorBrush Color="{Binding IndexWithinParentCollection, Mode=OneWay, Converter={StaticResource AltBGConverter}}" /&gt;
                      &lt;/Grid.Background&gt;
  </code></pre>
  
  <p>...and, when adding items to the collection, or modifying the collection, remember to set their Index within the collection:</p>
  
  <pre><code>myCollection.add(item);
  item.IndexWithinParentCollection = myCollection.Count;
  </code></pre>
  
  <p>Of course, if your collection changes often this approach will be costly to maintain, since you'll have to re-index your items, so I found it easier to store a reference to the parent collection within each item, then calculate the Index on-the-fly using .IndexOf() to avoid having to constantly update the index values every time the collection changes.</p>