Chitankensuru
Chitankensuru

Reputation: 11

Xamarin Forms Alternating BackgroundColor Listview in XAML

For a ListView in Xamarin Forms I'd like to implement an alternating background color for odd and even rows. Right now I have an IValueConverter in place. I'd like to pass the ListViewItem to the convert function.

public class BackgroundConverter : IValueConverter
{
    public object Convert (object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (!(value is int)) return null;
        int index = (int)value;

        if (index % 2 == 0)
            return Color.White;
        else
            return Color.Blue;
    }
....

The Xaml that I currently have in place:

....
<ResourceDictionary>
    <local:BackgroundConverter x:Key="bgColorPicker" />
</ResourceDictionary>
....
....
<ListView 
    x:Name="list" 
    RowHeight="130"
    SeparatorVisibility="None">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <ViewCell.View>
                    <Grid 
                        x:Name="listItem" 
                        Padding="10" 
                        ColumnSpacing="10"
                        BackgroundColor="{Binding ?, Converter={StaticResource bgColorPicker}}">

How should I implement this further? I tried several Bindings, but I'm not getting any closer. I'd love to get some help on this. It feels like it should be simple to do. But I haven't been able to make it work.

Upvotes: 1

Views: 3438

Answers (1)

eakgul
eakgul

Reputation: 3698

There is a way to do it programatically on both Xaml and Converter.

  • Pass both ListView and binded object to Converter
  • Find the indexOf the item on List
  • Decide the color

Sample Implemtation:

Converter:

using System.Collection;

public class BackgroundConverter : IValueConverter
{
    public object Convert (object value, Type targetType, object parameter, CultureInfo culture)
    {
        int index = 0;
        for(var itm in (parameter as ListView).ItemsSource)
            if(itm != value)
                index++;
            else
            {
                return (index%2==0)?Color.White:Color.Blue;
            }

    throw new InvalidOperationException("invalid parameters provided");
    }
}

Xaml:

< ListView 
    x:Name="list" 
    RowHeight="130"
    SeparatorVisibility="None">
    < ListView.ItemTemplate>
        < DataTemplate>
            < ViewCell>
                < ViewCell.View>
                    < Grid 
                    x:Name="listItem" 
                    Padding="10" 
                    ColumnSpacing="10"
                    BackgroundColor="{Binding ., Converter={StaticResource bgColorPicker},ConverterParameter={x:Reference list}}"
                        >

Upvotes: 3

Related Questions