Monday, July 2, 2012 12:12 PM | Comments

zebra-camoI’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);
        }
    }
}

 

Technorati Tags: ,,
blog comments powered by Disqus