Implementation of Collection View in .NET MAUI

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>

Step 3. The next step is to create the new class file example name as EmployeeModel.cs and it should be defined in the collection view DataTemplate.

Define the namespace with the name of the created class file.

xmlns:models="clr-namespace:CollectionView"

Define the created namespace name into collectionview DataTemplate.

<DataTemplate x:DataType="models:EmployeeModel">
public class EmployeeModel
{
    public string EmployeeName { get; set; }
    public string EmployeeGender { get; set; }
    public string EmployeeAge { get; set; }
}

Step 4. The next step is to bind the created list item in the view group and make all the individual items bind within the view.

<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>

Step 5. Next is to create the ItemSource ObervableProperty in viewmodel and define that DataType as ObservalbleCollection.

[ObservableProperty]

public ObservableCollection<EmployeeModel> employeeItemSource;

Step 6. Next is to define the created ItemSource inside the constructor and assign the property values to Itemsource to display on a visual mobile screen.

EmployeeItemSource = new ObservableCollection<EmployeeModel>();

EmployeeItemSource = new ObservableCollection<EmployeeModel>
{
    new EmployeeModel { EmployeeName = "Name : Manikandan", EmployeeAge = "Age : 27", EmployeeGender = "Gender : Male" },
    new EmployeeModel { EmployeeName = "Name : AjithKumar", EmployeeAge = "Age : 26", EmployeeGender = "Gender : Male" },
    new EmployeeModel { EmployeeName = "Name : Elavarsan", EmployeeAge = "Age : 25", EmployeeGender = "Gender : Male" },
    new EmployeeModel { EmployeeName = "Name : Pavithara", EmployeeAge = "Age : 27", EmployeeGender = "Gender : Female" },
    new EmployeeModel { EmployeeName = "Name : Kumar", EmployeeAge = "Age : 23", EmployeeGender = "Gender : Male" },
    new EmployeeModel { EmployeeName = "Name : Meera", EmployeeAge = "Age : 24", EmployeeGender = "Gender : Female" },
    new EmployeeModel { EmployeeName = "Name : Manikandan", EmployeeAge = "Age : 23", EmployeeGender = "Gender : Male" },
    new EmployeeModel { EmployeeName = "Name : Manikandan", EmployeeAge = "Age : 29", EmployeeGender = "Gender : Male" },
    new EmployeeModel { EmployeeName = "Name : Manikandan", EmployeeAge = "Age : 25", EmployeeGender = "Gender : Male" }
};

Output screen

Output screen

Conclusion

Hopefully, this article has given you sufficient information for you to create an MAUI collection view using viewmodel and run the app on both Android/iOS. Feel free to leave a comment if you would like me to further elaborate on anything within this article.


Similar Articles