How to change the background color of Selected item in CollectionView? .Net Maui
I saw the response to the item asked previously on this forum : how to change the background color of selected item in CollectionView. It works correctly (the selected item takes the background color when selected, LightSkyBlue in this case) when we select an item in the list. But when the item is selected by an event, the background color is not modify. The old selected item remains with he background color (LightSkyBlue ), and the new selected item takes the default background color (lightGray)
Here is the XAML extract :
<Button x:Name="btnCollection" Text="ActionCollections" Clicked="btnCollection_Clicked" WidthRequest="200"/>
<CollectionView x:Name="MaCollection" ItemsSource= "{Binding ItemsList}"
SelectionMode="Single"
SelectedItem="{Binding MySelected}"
MaximumHeightRequest="100" WidthRequest="300" >
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Label Text="{Binding .}" />
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="CommonStates">
<VisualState Name="Normal"></VisualState>
<VisualState Name="Selected">
<VisualState.Setters>
<Setter Property="BackgroundColor" Value="LightSkyBlue"></Setter>
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
and here the .cs
private string _mySelected;
public string MySelected
{
get { return _mySelected; }
set
{
if (_mySelected != value)
{
_mySelected = value;
OnPropertyChanged();
}
}
}
public ObservableCollection<String> ItemsList { get; } = new ObservableCollection<String>();
private void btnCollection_Clicked(object sender, EventArgs e)
{
MySelected = "maliste5"; // an item in the list
}