Wednesday, 29 January 2014

Alternating Rows with the LongListSelector

If you are familiar with the LongListSelector control in Windows Phone, you may have noticed that it does not natively support alternating row styles.  With regards to list items, you’re left with the ItemTemplate to determine the layout and appearance of your list items.

To change the background colour of your items, one possible workaround is to use a converter to evaluate a property on your bound item, and alternate between two sets of brushes.  I’ve created an AlternatingRowConverter to do just that.

Here, the converter is expecting an integer value and by doing a simple modulus we can switch between two SolidColorBrushes, which have been defined as public properties.
Here’s what our xaml looks like:

Notice that the PrimaryRowBrush and AlternateRowBrush can be defined in a number of ways, either by named value or hex, or creating the brush directly.

Within the LongListSelector.ItemTemplate we use a StackPanel to house the item.  The Background property of the StackPanel is bound to the Index property of a business object called Fruit.  The Converter takes the integer value and returns either the PrimaryRowBrush or AlternateRowBrush.
And here’s the result:

You can download the source code here.

No comments: