Alternating ListBox item background colours in WP7

I had a requirement today to implement alternating row colours in a Windows Phone 7 ListBox. After a bit of frustration with searching and only finding answers tht said “You can’t do it”, or that you need to add a property on the model to bind the background to, I eventually hit upon a nugget of common sense on this page.

Basically you need to create a converter class that will handle the alternation of backgrounds for you. It is ridiculously simple once you see it in action.

Step 1 : Create the converter.

public class AlternateRowColour : IValueConverter
{
bool isAlternate;
SolidColorBrush even = new SolidColorBrush(Colors.Transparent); // Set these two brushes to your alternating background colours.
SolidColorBrush odd = new SolidColorBrush(Color.FromArgb(255, 241, 241, 241));

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
isAlternate = !isAlternate;
return isAlternate ? even : odd ;
}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}

Step 2 : Add the converter to the page

<UserControl
 	...snip...
 	xmlns:conv="clr-namespace:MyApplication.Converters"
 	...snip...
 	>
	<UserControl.Resources>
		<conv:AlternateRowColour x:Key="RowColour" />
	</UserControl.Resources>
	...snip...
</UserControl>

Step 3 : Bind to the ListBox

<ListBox ItemsSource="{Binding}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <Grid Background="{Binding Converter={StaticResource RowColour}}">
        <!-- layout XAML -->
      </Grid>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

And you’re done.

This entry was posted in .NET, C# Snippets, Mango, Windows Phone, WP7. Bookmark the permalink.

One Response to Alternating ListBox item background colours in WP7

  1. Nit Picker says:

    Actually you bind to the Grid, not the Listbox(Item). That seeems to be important with WP7, since the ListboxItem accepted static colours, but threw an exception as soon as I tried to assign any kind of “{Binding}” to it: “read-only value”.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>