CollectionView in .Net MAUI

Introduction

In this article, we are going to learn about how to add CollectionView in .Net MAUI.

Prerequisites

Before starting to develop .Net MAUI apps, Visual Studio 2022 version 17.3 or greater needs to be installed with .NET Multi-platform App UI development workload with its default optional installation options.

  • For .Net iOS apps MAC machine is required along with XCode and Apple Id along with paid Apple Developer program.
  • Launch Visual Studio 2022 and "Create a new project" in the start window.

Implementation & Code

Add two New .Net MAUI Content Page (XAML) as CollectionViewSamplePage inside the Views folder,

Now go to CollectionViewSamplePage.xaml and add the code below,

<?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="MauiSampleAppFirst.Views.CollectionViewSamplePage"
             Title="CollectionViewSamplePage" BackgroundColor="#333333"
             Shell.TabBarIsVisible="False" Shell.NavBarIsVisible="True">

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="1*"/>
            <RowDefinition Height="9*"/>
        </Grid.RowDefinitions>

        <StackLayout Grid.Row="0" BackgroundColor="Transparent" Orientation="Horizontal" Margin="10">
            <Button Background="Blue" BorderColor="White" BorderWidth="1" TextColor="White" Text="Go to Last"
                    HorizontalOptions="StartAndExpand" Clicked="LastItemButton_Clicked"/>
            <Button Background="Maroon" BorderColor="White" BorderWidth="1" TextColor="White" Text="Back to Top"
                    HorizontalOptions="EndAndExpand" Clicked="FirstItemButton_Clicked"/>
        </StackLayout>

        <CollectionView Grid.Row="1" x:Name="playersCollectionView" ItemsSource="{Binding Players}">
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <ContentView>
                        <Frame BackgroundColor="#2b2b2b" CornerRadius="14" Margin="10">
                            <Grid>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="Auto"/>
                                    <RowDefinition Height="Auto"/>
                                </Grid.RowDefinitions>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="Auto"/>
                                    <ColumnDefinition Width="Auto"/>
                                </Grid.ColumnDefinitions>
                                <Ellipse Stroke="White" Grid.RowSpan="2"
                                         WidthRequest="60"
                                         HeightRequest="60"
                                         HorizontalOptions="Start"
                                         Fill="WhiteSmoke"
                                         StrokeThickness="1"
                                         Margin="0,0,10,0"/>
                                <Label Grid.Column="1" TextColor="White"
                                       Text="{Binding PlayerName}"
                                       FontAttributes="Bold"/>
                                <Label Grid.Row="1" TextColor="White"
                                       Grid.Column="1"
                                       Text="{Binding Country}"
                                       FontAttributes="Italic"
                                       VerticalOptions="End"/>
                            </Grid>
                        </Frame>
                    </ContentView>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
    </Grid>
</ContentPage>

Creating collectionview data

Create a model class called Players,

public class Player
{
    public int PlayerId { get; set; }
    public string PlayerName { get; set; }
    public string PlayerImage { get; set; }
    public string Country { get; set; }
}

Add the below code into xaml.cs file

Create ObservableCollection for CollectionView data source,

 ObservableCollection<Player> players = new ObservableCollection<Player>();
 public ObservableCollection<Player> Players { get { return players; } }

Now create data for ObservableCollection,

players.Add(new Player { PlayerId = 1, PlayerName = "Virat Kohi", PlayerImage = "icon.png", Country = "INDIA" });
players.Add(new Player { PlayerId = 2, PlayerName = "Rohit Sharma", PlayerImage = "icon.png", Country = "INDIA" });
players.Add(new Player { PlayerId = 3, PlayerName = "Shubhman Gill", PlayerImage = "icon.png", Country = "INDIA" });
players.Add(new Player { PlayerId = 4, PlayerName = "Shikhar Dhawan", PlayerImage = "icon.png", Country = "INDIA" });
players.Add(new Player { PlayerId = 5, PlayerName = "Suryakumar Yadav", PlayerImage = "icon.png", Country = "INDIA" });
players.Add(new Player { PlayerId = 6, PlayerName = "MahendraSingh Dhoni", PlayerImage = "icon.png", Country = "INDIA" });
players.Add(new Player { PlayerId = 7, PlayerName = "Jasprit Bumrah", PlayerImage = "icon.png", Country = "INDIA" });
players.Add(new Player { PlayerId = 8, PlayerName = "Hardik Pandya", PlayerImage = "icon.png", Country = "INDIA" });
players.Add(new Player { PlayerId = 9, PlayerName = "Shreyes Iyer", PlayerImage = "icon.png", Country = "INDIA" });
players.Add(new Player { PlayerId = 10, PlayerName = "Rishabh Pant", PlayerImage = "icon.png", Country = "INDIA" });
players.Add(new Player { PlayerId = 11, PlayerName = "Rvindra Jadeja", PlayerImage = "icon.png", Country = "INDIA" });

Set item source to Collectionview, 

playersCollectionView.ItemsSource = players;

Additional Properties

Scroll to the last item of the collection (add this code in .xaml.cs file inside button click event),

playersCollectionView.ScrollTo(players.Count);

Scroll to the first item of the collection (add this code in .xaml.cs file inside the button click event),

playersCollectionView.ScrollTo(1);

Pull to Refresh

<RefreshView IsRefreshing="{Binding IsRefreshing}"
             Command="{Binding RefreshCommand}">
      <CollectionView ItemsSource="{Binding Players}">
        ...
      </CollectionView>
</RefreshView>

Add logic to Refresh CollectionView in RefreshCommand (in xaml.cs or ViewModel class)

Item Selection in CollectionView

For single selection use (In xaml file inside CollectgionView),

SelectionMode="Single"

For multiple selection use (In xaml file inside CollectgionView),

SelectionMode="Multiple"

To get selected items, use (In xaml file inside CollectgionView),

SelectionChanged="OnCollectionViewSelectionChanged"

Get selected items,

void OnCollectionViewSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var previous = e.PreviousSelection;
    var current = e.CurrentSelection;
    ...
}

Header and Footer in CollectionView

To add simple header and footer text to collectionview,

<CollectionView ItemsSource="{Binding players}"
                Header="Players collectionview header"
                Footer="Players collectionview footer">
    ...
</CollectionView>

To add a custom view to the header and footer,

<CollectionView ItemsSource="{Binding players}">
    <CollectionView.Header>
        <StackLayout BackgroundColor="Gray">
            <Label Margin="10"
                   Text="Header Text"
                   FontAttributes="Bold" />
        </StackLayout>
    </CollectionView.Header>
    <CollectionView.Footer>
        <StackLayout BackgroundColor="Gray">
            <Label Margin="10,0,0,0"
                   Text="Footer text
                   FontSize="12"
                   FontAttributes="Bold" />
        </StackLayout>
    </CollectionView.Footer>
    ...
</CollectionView>

Add SwiptView with CollectionView item (Swipe to edit or delete):

(Note: SwipeView may not work with Windows)

<SwipeView Margin="0">
  <SwipeView.RightItems>
     <SwipeItems>
        <SwipeItemView>
           <Frame HasShadow="False" BackgroundColor="Red">
               <Label Text="Delete" TextColor="White" VerticalTextAlignment="Center" />
            </Frame>
        </SwipeItemView>

        <SwipeItemView>
            <Frame HasShadow="False" BackgroundColor="Green">
               <Label Text="Edit" TextColor="White" VerticalTextAlignment="Center"/>
             </Frame>
        </SwipeItemView>
    </SwipeItems>
</SwipeView.RightItems>

Output

Android

Android Collection View

Windows

Windows Collection View

Github url: https://github.com/Virendra3112/MauiSampleAppFirst.App/blob/master/Views/CollectionViewSamplePage.xaml 


Similar Articles