#1,001 – Setting an Alternating Background Color in an ItemsControl

The AlternationCount and AlternationIndex properties of controls inheriting from ItemsControl allow setting property values that alternate across the collection of items.

The AlternationCount property dictates how many unique styles you alternate between.  The most common value is 2, indicating that every other item has a particular style.  In the example below, we use these properties to set up an alternating background color.

        <AlternationConverter x:Key="altconvBackground">
            <SolidColorBrush Color="AliceBlue"/>
            <SolidColorBrush Color="White"/>

    <Grid Margin="10" >
        <ListBox ItemsSource="{Binding ActorList}" Width="200"
                <Style TargetType="{x:Type ListBoxItem}">
                    <Setter Property="Background"
                            Value="{Binding RelativeSource={RelativeSource Self}, Path=(ItemsControl.AlternationIndex), Converter={StaticResource altconvBackground}}"/>

We set an ItemContainerStyle because we want to set a property for a given ListBoxItem.  We then set the Background of each item to derive its value from the AlternationIndex property of the item.  The AlternationConverter is used to convert this index, 0 or 1, into a SolidColorBrush.


About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #1,001 – Setting an Alternating Background Color in an ItemsControl

  1. Pingback: Dew Drop – February 4, 2014 (#1716) | Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: