My proposal is to use a Converter class with additional DependencyProperties. When you intialize the converter, you define to which items collection it will refer and a list of alternate brushes for a background. It can look for example like this:
public class AlternateConverter : DependencyObject, IValueConverter
{
public List<SolidColorBrush> AlternateBrushes
{
get { return (List<SolidColorBrush>)GetValue(AlternateBrushesProperty); }
set { SetValue(AlternateBrushesProperty, value); }
}
public static readonly DependencyProperty AlternateBrushesProperty =
DependencyProperty.Register("AlternateBrushes", typeof(List<SolidColorBrush>),
typeof(AlternateConverter), new PropertyMetadata(new List<SolidColorBrush>()));
public object CurrentList
{
get { return GetValue(CurrentListProperty); }
set { SetValue(CurrentListProperty, value); }
}
public static readonly DependencyProperty CurrentListProperty =
DependencyProperty.Register("CurrentList", typeof(object),
typeof(AlternateConverter), new PropertyMetadata(null));
public object Convert(object value, Type targetType, object parameter, string language)
{ return AlternateBrushes[(CurrentList as IList).IndexOf(value) % AlternateBrushes.Count]; }
public object ConvertBack(object value, Type targetType, object parameter, string language)
{ throw new NotImplementedException(); }
}
Once you have it defined and create list of alternate brushes:
// somewhere in your DataContext
private List<SolidColorBrush> brushes = new List<SolidColorBrush> { new SolidColorBrush(Colors.Red), new SolidColorBrush(Colors.Blue) };
public List<SolidColorBrush> Brushes { get { return brushes; } }
You can use it like this:
<ListView x:Name="myList" ItemsSource={Binding MyItems}>
<ListView.Resources>
<local:AlternateConverter CurrentList="{Binding ElementName=myList, Path=ItemsSource}"
AlternateBrushes="{Binding Brushes}"
x:Key="AlternateConverter"/>
</ListView.Resources>
<ListView.ItemTemplate>
<DataTemplate>
<Border Background="{Binding Converter={StaticResource AlternateConverter}}">
<!-- your itemtemplate -->
</Border>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
This solution should work, though it may have problem when you have IList of value types. Also here shouldn't be problems with deferred creation, as it retrives the index directly from list.