Introduction
In this article, I will explain MAUI Collection View implementation using Visual Studio 2022. .NET MAUI Collection View is a view for presenting lists of data using different layout specifications. Collection View should be used for presenting lists of data that require scrolling or selection. A bindable layout can be used when the data to be displayed doesn't require scrolling or selection.
Important Notes
- If the Collection View is required to refresh as items are added removed or changed in the underlying collection should be an IEnumerable collection that sends property change notifications such as ObservableCollection.
- When using CollectionView, never set the root element of your DataTemplate objects to a ViewCell. This will result in an exception being thrown because CollectionView has no concept of cells.
- CollectionView inside a VerticalStackLayout can stop the CollectionView scrolling and can limit the number of items that are displayed. In this situation, replace the VerticalStackLayout with a Grid.
Step 1. Create a new Page with View Model and those should be registered in Mauiprogram.cs and AppShell.cs. I have created an example page as MainPage.
Register view and ViewModel in Mauiprogram.cs
builder.Services.AddTransient<MainPage>();
builder.Services.AddTransient<MainViewModel>();
Routing.RegisterRoute(nameof(MainPage), typeof(MainPage));
Step 2. The next step is to write a collection view template in MainPage.Xaml file and define the display widget inside the DataTemplate.
<CollectionView x:Name="EmployeeCollectionView"
EmptyView="No Record Available"
ItemsLayout="VerticalList"
ItemsSource="{Binding EmployeeItemSource, Mode=TwoWay}"
SelectionChangedCommand="{Binding Path=BindingContext.EmployeeItemClickedCommand, Source={Reference EmployeeCollectionView}}"
SelectionChangedCommandParameter="{Binding Path=SelectedItem, Source={x:Reference EmployeeCollectionView}}"
SelectionMode="Single">
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="models:EmployeeModel">
<Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="CommonStates">
<VisualState Name="Selected">
<VisualState.Setters>
<Setter Property="BackgroundColor" Value="{StaticResource TransparentColor}" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Border Margin="10,5" Padding="0"
BackgroundColor="WhiteSmoke"
Stroke="Green"
StrokeThickness="1"
StrokeShape="RoundRectangle 5">
<StackLayout Orientation="Vertical" Padding="10">
<Label Text="{Binding EmployeeName}" TextColor="Black" FontAttributes="Bold"/>
<Label Text="{Binding EmployeeGender}" TextColor="Black" FontAttributes="Bold"/>
<Label Text="{Binding EmployeeAge}" TextColor="Black" FontAttributes="Bold"/>
</StackLayout>
</Border>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>


Join the conversation! Your thoughts help the community grow.