Alternating Row Color in ListView

Alternating row colours are not there, by default, with the ListView. Here’s an easy way to to do it in UWP. I originally found this page on MSDN but it was old - for .NET 3.0 - and didn’t work in UWP. I later found this article by Ben Dewey which worked. My post is a brief version of Ben’s post.

The easiest way to achieve alternating rows is by creating your own ListView class and adding dependency properties to specify the row colours. The dependency properties allow you to define the colours in XAML (i.e. you can set your ThemeResource). You could do without the dependency properties and just hard-code some colours but I wouldn’t suggest it.

[code lang="csharp”] public class AlternatingRowListView : ListView { public static readonly DependencyProperty OddRowBackgroundProperty = DependencyProperty.Register("OddRowBackground", typeof(Brush), typeof(AlternatingRowListView), null); public Brush OddRowBackground { get { return (Brush)GetValue(OddRowBackgroundProperty); } set { SetValue(OddRowBackgroundProperty, (Brush)value); } }

public static readonly DependencyProperty EvenRowBackgroundProperty = DependencyProperty.Register("EvenRowBackground", typeof(Brush), typeof(AlternatingRowListView), null); public Brush EvenRowBackground { get { return (Brush)GetValue(EvenRowBackgroundProperty); } set { SetValue(EvenRowBackgroundProperty, (Brush)value); } }

protected override void PrepareContainerForItemOverride(DependencyObject element, object item) { base.PrepareContainerForItemOverride(element, item); var listViewItem = element as ListViewItem; if (listViewItem != null) { var index = IndexFromContainer(element);

if ((index + 1) % 2 == 1) { listViewItem.Background = OddRowBackground; } else { listViewItem.Background = EvenRowBackground; } }

} } [/code]

The above code is relatively simple. Based on the index of the row it sets the colour of the row.

To implement this in your XAML, you would do something like this

[code lang="xml”]

<controls:AlternatingRowListView x:Name="Comps” EvenRowBackground=”{ThemeResource MyEvenRowBrush}” OddRowBackground=”{ThemeResource MyOddRowBrush}“>

controls:AlternatingRowListView.ItemTemplate </controls:AlternatingRowListView.ItemTemplate> </controls:AlternatingRowListView> [/code]