I have created a Windows Phone 8.1 run-time app.
I am using the ListView control.
I want to alternate the each background row color.
After searching I found this link a previous answer.
But this gives errors in the markup. For one thing there is no 'AlternationCount' property. I am assuming this is because it is not SilverLight but RT?
If anyone can send me a link as I am struggerling to find a simple example. even better a simple code example would be appreciated.
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.