Home > OS >  How can I make a list view have alternating background colors? NET MAUI
How can I make a list view have alternating background colors? NET MAUI

Time:06-08

I am trying to create a list view where the background color alternates for each entry in the list. Is there a way to do this in MAUI?

CodePudding user response:

This can be done in multiple ways.And the method often recommended is through a DataTemplateSelector.

1.Create a DataTemplateSelector that holds two templates and selects them based on the index of the item:

public class AlternateColorDataTemplateSelector: DataTemplateSelector
{
    public DataTemplate EvenTemplate { get; set; }
    public DataTemplate UnevenTemplate { get; set; }

    protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
    {
        // TODO: cast `Monkey` to your Item 
        return ((List<Monkey>)((ListView)container).ItemsSource).IndexOf(item as Monkey) % 2 == 0 ? EvenTemplate : UnevenTemplate;
    }
}

2.In XAML, we can define two templates, one with the alternate color and one with the normal color.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiApp0606.MainPage"
             xmlns:local="clr-namespace:MauiApp0606"
             >

    <ContentPage.Resources>
        <ResourceDictionary>
            <DataTemplate x:Key="evenTemplate">
                <ViewCell>
                    <Grid BackgroundColor="White">
                        <Label Text="{Binding Name}" HorizontalOptions="Center" VerticalOptions="Center" />
                    </Grid>
                </ViewCell>
            </DataTemplate>
            <DataTemplate x:Key="unevenTemplate">
                <ViewCell>
                    <Grid BackgroundColor="LightGray">
                        <Label Text="{Binding Name}" TextColor="White" HorizontalOptions="Center" VerticalOptions="Center" />
                    </Grid>
                </ViewCell>
            </DataTemplate>
            <local:AlternateColorDataTemplateSelector x:Key="alternateColorDataTemplateSelector"
                EvenTemplate="{StaticResource evenTemplate}"
                UnevenTemplate="{StaticResource unevenTemplate}" />
            
        </ResourceDictionary>
    </ContentPage.Resources>
 
        <VerticalStackLayout Spacing="25" Padding="30">

            <ListView ItemsSource="{Binding Monkeys}" ItemTemplate="{StaticResource alternateColorDataTemplateSelector}">

            </ListView>

        </VerticalStackLayout>
</ContentPage>
  • Related