Articles in this section
Category / Section

How to apply selected item background color in .NET MAUI ListView (SfListView)?

5 mins read

In the .NET MAUI ListView (SfListView), the item background color will not be displayed for the selected item if the background color is defined for the ItemTemplatewhich is the actual behavior in the framework. However, this can be achieved through a workaround by defining a property in the data model and using a custom converter.

Define the IsSelected property in the model class to indicate whether the item is selected. This property will be updated when the selection is performed using the SelectionChanged event. Based on this property, the background color of the View defined in the ItemTemplate property can be changed by a custom converter class.

C#

The SfListView SelectionChanged EventArgs contains two properties: AddedItems and RemovedItems. Here, get the data of the selected item.

public class Behavior:Behavior<SfListView>
{
    private SfListView listView;
 
    protected override void OnAttachedTo(SfListView bindable)
    {
        listView = bindable;
        listView.SelectionChanged += ListView_SelectionChanged;
        base.OnAttachedTo(bindable);
    }
 
    #region CallBacks
    private void ListView_SelectionChanged(object sender, ItemSelectionChangedEventArgs e)
    {
        for (int i = 0; i < e.AddedItems.Count; i++)
        {
            var item = e.AddedItems[i];
            (item as MusicInfo).IsSelected = true;
        }
        for (int i = 0; i < e.RemovedItems.Count; i++)
        {
            var item = e.RemovedItems[i];
            (item as MusicInfo).IsSelected = false;
        }
    }
    #endregion
 
    protected override void OnDetachingFrom(SfListView bindable)
    {
        listView.SelectionChanged -= ListView_SelectionChanged;
        listView = null;
        base.OnDetachingFrom(bindable);
    }
}

XAML

Bind the ItemTemplate Background using the Converter value, where the background color of the ItemTemplate will change based on the selected items.

<ContentPage>
<ContentPage.BindingContext>
        <local:SelectionViewModel x:Name="viewModel"/>
    </ContentPage.BindingContext>
 
    <ContentPage.Resources>
        <ResourceDictionary>
            <local:SelectionBoolToImageConverter x:Key="BoolToImageConverter"/>
            <local:SelectionBoolToBackGroundColorConverter x:Key="BoolToColorConverter"/>
        </ResourceDictionary>
    </ContentPage.Resources>
 
    <Grid Margin="0">
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <listView:SfListView x:Name="listView" 
                             ItemsSource="{Binding MusicInfo}"
                             SelectionGesture="Tap"
                             SelectionMode="Single" 
                             AutoFitMode="Height"
                             ItemSpacing="5"
                             ItemSize="70">
            <listView:SfListView.Behaviors>
                <local:Behavior/>
            </listView:SfListView.Behaviors>
             
            <listView:SfListView.ItemTemplate>
                <DataTemplate x:Name="ItemTemplate" >
                    <Grid x:Name="grid" RowSpacing="0" ColumnSpacing="0" BackgroundColor="{Binding Path=IsSelected,  Converter={StaticResource BoolToColorConverter}}">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="*" />
                            <RowDefinition Height="1" />
                        </Grid.RowDefinitions>
                        <Grid RowSpacing="0" Grid.Row="0" ColumnSpacing="0">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="40" />
                                <ColumnDefinition Width="*" />
                                <ColumnDefinition Width="Auto" />
                            </Grid.ColumnDefinitions>
                            <Image Source="{Binding SongThumbnail}"
                     HeightRequest="35"
                     WidthRequest="35"
                     VerticalOptions="Center"
                     HorizontalOptions="Center"/>
 
                            <Grid Grid.Column="1"
                    RowSpacing="1"
                    Padding="15,0,0,0"
                    VerticalOptions="Center">
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="*" />
                                    <RowDefinition Height="*" />
                                </Grid.RowDefinitions>
 
                                <Label LineBreakMode="NoWrap"
                       TextColor="#474747"
                       Text="{Binding SongTitle}" FontSize="18" />
                                <Grid RowSpacing="0"
                      ColumnSpacing="0" Padding="0,0,0,5"
                      Grid.Row="1">
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="Auto" />
                                        <ColumnDefinition Width="0.4*" />
                                    </Grid.ColumnDefinitions>
 
                                    <Label TextColor="#474747" LineBreakMode="NoWrap"
                         Text="{Binding SongAuther}" FontSize="12" VerticalTextAlignment="Center" />
                                    <Label TextColor="#474747" Margin="0,0,10,0"
                         Grid.Column="1" LineBreakMode="NoWrap" VerticalTextAlignment="Center" HorizontalTextAlignment="End"
                         Text="{Binding SongSize}" FontSize="12" />
                                </Grid>
                            </Grid>
 
                            <Image Grid.Column="2" x:Name="selectionImage" Margin="10,0,10,0"
                     HeightRequest="30" WidthRequest="30" VerticalOptions="Center" HorizontalOptions="Center"
                     IsVisible="True"
                     Source="{Binding Path=IsSelected, Converter={StaticResource BoolToImageConverter}}"/>
                        </Grid>
                        <StackLayout Grid.Row="1"  HeightRequest="1"/>
                    </Grid>
                </DataTemplate>
            </listView:SfListView.ItemTemplate>
        </listView:SfListView>
    </Grid>
</ContentPage>

Change the background color of the view based on the IsSelected property using the SelectionBoolToBackgroundColorConverter class.

public class SelectionBoolToBackgroundColorConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    return (bool)value == true ? Color.FromRgb(211,211,211) : Color.White;
  }
 
  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
    throw new NotImplementedException();
  }
}
Output

 To apply the selected item background color when the ItemTemplate view has a background color in .NET MAUI ListView (SfListView)


Download the complete sample on GitHub.

 

Conclusion:
I hope you enjoyed learning how to apply selected item background color in .NET MAUI ListView.
Refer to our 
.NET MAUI ListView feature tour page to learn about its other groundbreaking feature representations. You can explore our .NET MAUI ListView documentation to understand how to present and manipulate data.
For current customers, check out our .NET MAUI components from the 
License and Downloads page. If you are new to Syncfusion®, try our 30-day free trial to check out our .NET MAUI ListView and other .NET MAUI components.
Please let us know in the comments section if you have any queries or require clarification. 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  to leave a comment
Access denied
Access denied