Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change background color of listview selected item in Xamarin Forms Cross Platform without a custom renderer

how can I change the selected color of a list view selected item in Xamarin Forms Cross Platform?

I was able to change it using the answer in this question How can I change background color of a ListView in Xaml?

but on first appear the selected item is with the default background color (Orange).

Any suggestions?

I wonder why in 2019 (nearly 2020) there isn't an out of the box way to change this basic and common property easly.

Thanks.

like image 754
Giuseppe Terrasi Avatar asked Feb 01 '26 18:02

Giuseppe Terrasi


1 Answers

The below code works perfectly for me. However, it iterates the entire ItemsSource for resetting the background of the previously selected item. You can store it and reset it if you wish to optimize it. Hope this helps.

<ListView x:Name="contactList" ItemsSource="{Binding PlatformsList}" ItemTapped="contactList_ItemTapped"
             VerticalOptions="CenterAndExpand" HorizontalOptions="FillAndExpand">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Label TextColor="Black" Margin="10,0" Text="{Binding PlatformName}" BackgroundColor="{Binding Background}" VerticalOptions="Center" />
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

private void contactList_ItemTapped(object sender, ItemTappedEventArgs e)
{
    var selectedItem = e.Item as PlatformInfo;
    selectedItem.ItemBackground = Color.Aqua;

    foreach(var item in this.contactList.ItemsSource)
    {
        if (item != selectedItem)
            (item as PlatformInfo).ItemBackground = Color.Transparent;
    }
}
like image 51
Harikrishnan Avatar answered Feb 03 '26 09:02

Harikrishnan