I am working on MAUI technology and developing Windows Application So, I have a requirement to pre-select the item in collection view and that item need to be highlighted. so, I have checked the sample code of microsoft document there also have the same issue.
Sample Microsoft Document URL https://learn.microsoft.com/en-us/dotnet/maui/user-interface/controls/collectionview/selection?view=net-maui-7.0#multiple-preselection
So, I tried below code. It's working but i am unable to highlight the item with background color.
DetailsPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="iOSCollectionViewPreselectedTEST.NewPage1"
Title="DetailsPage">
<CollectionView ItemSizingStrategy="MeasureAllItems" x:Name="collView"
ItemsSource="{Binding Items}"
SelectedItem="{Binding SelectedItem, Mode=TwoWay}"
SelectionMode="Single" SelectionChanged="CollectionView_SelectionChanged">
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Vertical" Span="2"/>
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<VerticalStackLayout>
<Label Text="{Binding .}" VerticalOptions="Center" />
<VisualStateManager.VisualStateGroups >
<VisualStateGroup Name="CommonStates">
<VisualState Name="Normal" />
<VisualState Name="Selected">
<VisualState.Setters>
<Setter Property="BackgroundColor" Value="Blue" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</VerticalStackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</ContentPage>
DetailsPage.xaml.cs
public partial class DetailsPage : ContentPage
{
public ObservableCollection<string> Items { get; } = new ObservableCollection<string>(new List<string> {
"Employee1", "Employee2", "Employee3", "Employee4"
});
public string SelectedItem { get; set; }
public DetailsPage()
{
InitializeComponent();
BindingContext = this;
SelectedItem = Items[1];
OnPropertyChanged(nameof(SelectedItem));
}
private void CollectionView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var preSelectedItem = e.CurrentSelection;
}
}
Yes, it is just the case as you said.
And there is a known issue about this, you follow it up here: CollectionView Pre Select Item background color not change on windows.
Thanks for your support for maui.
Best Regards.