A Simple IndexingObservableCollection for Zebra-Striping Rows
Join the DZone community and get the full member experience.
Join For FreeZebra-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, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Turbocharge Ab Initio ETL Pipelines: Simple Tweaks for Maximum Performance Boost
-
Front-End: Cache Strategies You Should Know
-
What Is Envoy Proxy?
-
13 Impressive Ways To Improve the Developer’s Experience by Using AI
Comments