.NET Zone is brought to you in partnership with:

Matt is based in Chicago and works at Clarity Consulting, focusing on ASP.NET MVC, Windows Phone, and Windows 8. He can be found on twitter @MattHidinger, blogging at matthidinger.com, working on various open source projects, and participating in the local community. Matt is a DZone MVB and is not an employee of DZone and has posted 16 posts at DZone. You can read more from them at their website. View Full User Profile

A Simple IndexingObservableCollection for Zebra-Striping Rows

07.02.2012
| 1970 views |
  • submit to reddit
I’m currently wrapping up a Windows Phone project and thought this would be a good time to share some of the more reusable stuff we needed.

Zebra-striping alternate rows

This particular app displays a lot of tabular data, so we wanted to zebra-stripe the rows to make them easier to discern. At first we tried using a ValueConverter to get the index of the current container, but this method didn’t end up working with the Telerik DataBoundListBox.

Instead, we wrote a simple IndexingObservableCollection that will automatically populate the Index of each item as it’s added to the collection. This method also works with the infinite scrolling feature of Telerik’s listbox – which we actually needed anyway.

IndexingObservableCollection

To use it, you have to implement the IIndexable interface which ensure an Index property on your model. Then simply replace the ObservableCollection property on your view-model with the following IndexingObservableCollection.

public class IndexingObservableCollection<T> : ObservableCollection<T> where T : IIndexable
{
    protected override void InsertItem(int index, T item)
    {
        item.Index = index;
        base.InsertItem(index, item);
    }

    protected override void SetItem(int index, T item)
    {
        item.Index = index;
        base.SetItem(index, item);
    }
}

public interface IIndexable
{
    int Index { get; set; }
}

 

Tweaking your model

Below is a sample model that could be used for displaying a list of products. In this case I’m returning a specific Brush for odd-numbered rows, and the XAML Grid simply binds Background="{Binding Background}"

public class ProductRow : IIndexable
{
    public int Index { get; set; }

    public string ProductName { get; set; }

    public string Price { get; set; }

    public Brush Background
    {
        get
        {
            return Index % 2 == 1
                    ? new SolidColorBrush(Colors.DarkGray)
                    : new SolidColorBrush(Colors.White);
        }
    }
}
Published at DZone with permission of Matt Hidinger, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)