Articles in this section
Category / Section

How to set background color alternatively in Xamarin.Forms ListView (SfListView)?

2 mins read

You can change the BackgroundColor of ItemTemplate loaded in the Xamarin.Forms SfListView based on the value changed in Trigger with consideration of Selection.

XAML

Defined Trigger for the parent element of SfListView ItemTemplate and bind the model class property to change the Background color of the item.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:RowStyle"
             xmlns:listView="clr-namespace:Syncfusion.ListView.XForms;assembly=Syncfusion.SfListView.XForms"
             x:Class="RowStyle.MainPage">
 
    <ContentPage.BindingContext>
        <local:ContactsViewModel x:Name="viewModel"/>
    </ContentPage.BindingContext>
 
    <ContentPage.Resources>
        <ResourceDictionary>
            <local:IndexToColorConverter x:Key="IndexToColorConverter"/>
        </ResourceDictionary>
    </ContentPage.Resources>
    
    <ContentPage.Content>
        <listView:SfListView x:Name="listView" ItemsSource="{Binding Items}" ItemSize="50" SelectionMode="SingleDeselect" 
                             SelectionChanging="ListView_SelectionChanging" SelectionBackgroundColor="Beige">
            <listView:SfListView.ItemTemplate>
                <DataTemplate>
                    <Grid Padding="10,0,0,0"  x:Name="grid">
                        <Grid.Triggers>
                            <DataTrigger TargetType="Grid" Binding="{Binding Source={x:Reference grid},
                                       Path=BindingContext.IsSelected}" Value="False">
                                <Setter Property="BackgroundColor" Value="{Binding ., Converter={StaticResource IndexToColorConverter},ConverterParameter={x:Reference listView}}" />
                            </DataTrigger>
                            <DataTrigger TargetType="Grid" Binding="{Binding Source={x:Reference grid},
                                       Path=BindingContext.IsSelected}" Value="True">
                                <Setter Property="BackgroundColor" Value="SlateBlue" />
                            </DataTrigger>
                        </Grid.Triggers>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="*" />
                            <RowDefinition Height="*" />
                        </Grid.RowDefinitions>
                        <Label LineBreakMode="NoWrap" 
                   VerticalTextAlignment="End"
                   Text="{Binding ContactName}"/>
                        <Label Grid.Row="1"
                   VerticalTextAlignment="Start"
                   Text="{Binding ContactNumber}"/>
                    </Grid>
                </DataTemplate>
            </listView:SfListView.ItemTemplate>
        </listView:SfListView>
    </ContentPage.Content>
</ContentPage>

C#

Create model class property to indicate whether the item is selected or not. The background color will be updated based on the property value.

 

namespace ListViewXamarin
{
    public class Contacts : INotifyPropertyChanged
    {
        private bool isSelected;
 
        public bool IsSelected
        {
            get { return isSelected; }
            set
            {
                if (isSelected != value)
                {
                    isSelected = value;
                    this.RaisedOnPropertyChanged("IsSelected");
                }
            }
        }
    }
}

C#

Changing the IsSelected property in the SelectionChanging event of ListView.

ListView.SelectionChanging += ListView_SelectionChanging;
 
private void ListView_SelectionChanging(object sender, ItemSelectionChangingEventArgs e)
{
    for (int i = 0; i < e.AddedItems.Count; i++)
    {
        var item = e.AddedItems[i] as Contacts;
        item.IsSelected = true;
    }
 
    for (int i = 0; i < e.RemovedItems.Count; i++)
    {
        var item = e.RemovedItems[i] as Contacts;
        item.IsSelected = false;
    }
}

C#

Coverter to apply the alternate row style based on the index value of items.

namespace ListViewXamarin 
{
    public class IndexToColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var listview = parameter as SfListView;
            return listview.DataSource.DisplayItems.IndexOf(value) % 2 == 0 ? Color.LightGray : Color.Aquamarine;
        }
 
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

Output

Image for alternate row style in SfListView

View sample in GitHub   


Conclusion

I hope you enjoyed learning about how to set background color alternatively in Xamarin.Forms ListView (SfListView).

You can refer to our Xamarin.Forms ListView feature tour page to know about its other groundbreaking feature representations. You can also explore our Xamarin.Forms ListView documentation to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied