ItemsCollection and alternate row coloring

itemscontrol, styles, wpf

Solution

Add `AlternationCount="2"` to your ItemsControl.

Then add this to your ItemContainerStyle to get alternating red/blue items:

<Style.Triggers>
  <Trigger Property="ItemsControl.AlternationIndex" Value="0">
    <Setter Property="Control.Background" Value="Red"></Setter>
  </Trigger>
  <Trigger Property="ItemsControl.AlternationIndex" Value="1">
    <Setter Property="Control.Background" Value="Blue"></Setter>
  </Trigger>
</Style.Triggers>

Edit: you need to have the .NET 3.0/3.5 SP1.

Problem

I've got an itemscollection and I want to have alternate row colouring, I've looked about how to do this but can't find anything, I think this should be simple but maybe I'm missing something. It's WPF btw. ``` <Grid> <ItemsControl Name="itemsControl"> <ItemsControl.ItemTemplate> <DataTemplate> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="80"/> </Grid.ColumnDefinitions> <TextBlock Grid.Column="0" Text="{Binding Path=name}" VerticalAlignment="Center"/> <TextBlock Grid.Column="1" Text="{Binding Path=something}" VerticalAlignment="Center"/> <Button Grid.Column="2" Content="Launch" Tag="{Binding}" Height="25" VerticalAlignment="Center" Click="Button_Click"/> </Grid> </DataTemplate> </ItemsControl.ItemTemplate> <ItemsControl.ItemContainerStyle> <Style> <Setter Property="Control.Margin" Value="5"/> </Style> </ItemsControl.ItemContainerStyle> </ItemsControl> <Button Height="23" HorizontalAlignment="Right" Margin="0,0,12,12" Name="button1" VerticalAlignment="Bottom" Width="75" Click="button1_Click">Button</Button> </Grid> ```

Original source