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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With