Very quick Xamarin How-To this week with a simple converter. Alternating row colours in a CollectionView is quite often a design requirement and I wanted to create a simple, reusable converter to solve this.

The Converter

using System;
using System.Globalization;
using System.Linq;
using Xamarin.Forms;
using Xamarin.Forms.Internals;

namespace XhtCollectionViewAlternatingRowColor.Converters
{
    public class IndexToColorConverter : IValueConverter
    {
        public Color EvenColor { get; set; }

        public Color OddColor { get; set; }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var collectionView = parameter as CollectionView;

            return collectionView.ItemsSource.Cast().IndexOf(value) % 2 == 0 ? EvenColor : OddColor;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

Using the Converter in XAML





    
        

        
    

    
        
    

    
        
            
                
                    
                        
                
            
        
    


There you go, nice and simple, easy to follow and reuse! As always full source code available here.

By |2021-10-20T10:46:56+10:00October 15th, 2021|Categories: Xamarin.Forms|Tags: , , |2 Comments

About the Author:

Toby is an experienced Xamarin.Forms developer. His passion & willingness to learn, drives his quality and career. Toby currently works in Brisbane and is excited to see what the city has to offer in this growing IT hub.

2 Comments

  1. Bernhard P. October 19, 2021 at 14:24 - Reply

    Despite the fact that it works great, the ToList copy in each call of the converter seems a really bad example. A list of 10 items would create 20 list copies in your example.

    I think it would be way cleverer to type check it and cast it to prevent all those allocations that on mobile are really not nessecary.

    but none the less. a cool sample! keep up the cool blogs

    • Toby Field October 20, 2021 at 10:39 - Reply

      Hi Bernhard,
      That’s a very good point you make! I have updated the solution accordingly.

Leave A Comment