Xamarin.Forms - Using ListView HeaderTemplate And FooterTemplate To Display Data

The ListView Headers and Footers are Text or View to display at the beginning and end of a list, separate from the list's data. Headers and footers can be bound to a data source independently from the ListView's data source.

In this article, we will learn how to use ListView HeaderTemplate and FooterTemplate to display data from our ViewModel like total of items and sum of values in a Xamarin.Forms Application using Visual Studio Community 2017.

Creating a Xamarin.Forms Project

Open Visual Studio 2017 Community. Go to File-> New Project.
Select Cross-Platfom -> Xamarin Platform App (Xamarin.Forms or Native) -> click OK.
Set the name of Project XF_Products;

Now, set the settings as given below.

  • Blank app
  • Forms
  • Portable Class Library (PCL)

Now, click OK.

Xamarin

Click OK after selecting the Target version and Minimum version of your Universal Windows Project.

Xamarin

Now, your project is created and you are ready for development.

A project containing the App.xaml and MainPage.xaml pages has been created in the Portable project. In the code-behind of the App.xaml file, we have the App.cs class which will contain the shared code and which we will use in this article.

In the App.cs file, include the following code where we set the main page of the application as the MainPage.

  1. using Xamarin.Forms;  
  2.   
  3. namespace XF_Products  
  4. {  
  5.     public partial class App : Application  
  6.     {  
  7.         public App()  
  8.         {  
  9.             InitializeComponent();  
  10.   
  11.             MainPage = new NavigationPage(new XF_Products.MainPage());  
  12.         }  
  13.   
  14.         protected override void OnStart()  
  15.         {  
  16.             // Handle when your app starts  
  17.         }  
  18.   
  19.         protected override void OnSleep()  
  20.         {  
  21.             // Handle when your app sleeps  
  22.         }  
  23.   
  24.         protected override void OnResume()  
  25.         {  
  26.             // Handle when your app resumes  
  27.         }  
  28.     }  
  29. }   

Defining the Model and Service

Create a Model folder in the project. Inside Model folder, create the Product Class with the following code.

  1. namespace XF_Products.Model  
  2. {  
  3.     public class Product  
  4.     {  
  5.         public string Name { get; set; }  
  6.         public decimal Price { get; set; }  
  7.     }  
  8. }   

Also, create the ProductService class inside Model folder with code below.

  1. using System.Collections.ObjectModel;  
  2.   
  3. namespace XF_Products.Model  
  4. {  
  5.     public class ProductService  
  6.     {  
  7.         public ObservableCollection<Product> GetAll { get; private set; }  
  8.    
  9.          public ProductService()  
  10.         {  
  11.                 GetAll = new ObservableCollection<Product> {  
  12.                 new Product { Name = "HP Stream LapTop", Price = 199.00M },  
  13.                 new Product { Name = "Western Digital 1 TB", Price = 64.99M},  
  14.                 new Product { Name = "Casio Calculator", Price = 7.79M },  
  15.                 new Product { Name = "Microsoft Surface Pro", Price = 854.19M },  
  16.                 new Product { Name = "Dell 27 LCD Monitor", Price = 168.36M },  
  17.                 new Product { Name = "HP 27 LED Monitor", Price = 178.50M },  
  18.                 new Product { Name = "Memorex Lens Cleaner", Price = 9.98M },  
  19.             };  
  20.         }  
  21.     }  
  22. }   

This code is used to populate a list of products.

Defining the ViewModel

Now, create the folder ViewModel in the Project and then create the ProductsViewModel class with the following code.

  1. using System.Collections.Generic;  
  2. using System.Linq;  
  3. using XF_Products.Model;  
  4.   
  5. namespace XF_Products.ViewModel  
  6. {  
  7.     public class ProductsViewModel  
  8.     {  
  9.         public IList<Product> Items { get; private set; }  
  10.         public int ItemsCount { get; private set; }  
  11.         public decimal ItemsSummary { get; private set; }  
  12.   
  13.         public ProductsViewModel()  
  14.         {  
  15.             var service = new ProductService();  
  16.             Items = service.GetAll.OrderBy(c => c.Name).ToList();  
  17.             ItemsCount = service.GetAll.Count;  
  18.             ItemsSummary = service.GetAll.Sum(p => p.Price);  
  19.         }  
  20.     }  
  21. }   

This code defines the proprerties Items, ItemsCount, and ItemsSummary that we will use in our View. The class constructor is used to get the list of product ordered by name, the items total of the list and the sum of product’s price list.

Defining the View: MainPage

Let's now set the code of the MainPage.xaml view as below 

  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  4.              xmlns:local="clr-namespace:XF_Products"  
  5.              x:Class="XF_Products.MainPage"  
  6.              Title="Products Price">  
  7.   
  8.     <ListView  
  9.         x:Name="ContatosListView" HasUnevenRows="True"  
  10.         ItemsSource="{Binding Items}" Header="{Binding}" Footer="{Binding}">  
  11.         <ListView.ItemTemplate>  
  12.             <DataTemplate>  
  13.                 <ViewCell>  
  14.                     <StackLayout Orientation="Horizontal">  
  15.                         <Label Text="{Binding Name}" HorizontalOptions="Start" />  
  16.                         <Label Text="{Binding Price, StringFormat='{0:C2}'}"  HorizontalOptions="EndAndExpand" TextColor="Blue" />  
  17.                     </StackLayout>  
  18.                 </ViewCell>   
  19.             </DataTemplate>  
  20.         </ListView.ItemTemplate>  
  21.         <ListView.HeaderTemplate>  
  22.             <DataTemplate>  
  23.                 <ContentView BackgroundColor="Beige">  
  24.                     <Label Margin="10" HorizontalOptions="CenterAndExpand" Text="{Binding ItemsCount, StringFormat='Items Total : {0}'}"  TextColor="Black"/>  
  25.                 </ContentView>  
  26.             </DataTemplate>  
  27.         </ListView.HeaderTemplate>  
  28.         <ListView.FooterTemplate>  
  29.             <DataTemplate>  
  30.                 <ContentView BackgroundColor="Aquamarine">  
  31.                     <Label Margin="10" Text="{Binding ItemsSummary, StringFormat='Total: {0:C2}'}" TextColor="Blue" HorizontalTextAlignment="End"/>  
  32.                 </ContentView>  
  33.             </DataTemplate>  
  34.         </ListView.FooterTemplate>  
  35.     </ListView>  
  36.   
  37. </ContentPage>   

This code defines the ListView ItemsSource property by using the databinding for the products list of Items.

We also define the Header and Footer using the {Binding} notation without defining a Source or Path. Doing so XAML understands that the object that will be used for the Binding will be the same as the current BindingContext. Because ListView propagates this object to the Header and Footer templates, this is not necessary.

Next we set the HeaderTemplate and FooterTemplate configured to display the ItemsCount and ItemsSummary properties.

Finally open the MainPage.xaml.cs file and include the code below 

  1. using Xamarin.Forms;  
  2. using XF_Products.ViewModel;  
  3.   
  4. namespace XF_Products  
  5. {  
  6.     public partial class MainPage : ContentPage  
  7.     {  
  8.         public MainPage()  
  9.         {  
  10.             InitializeComponent();  
  11.             BindingContext = new ProductsViewModel();  
  12.         }  
  13.     }  
  14. }   

This code is creating an instance of our ViewModel and assigning it to the BindingContext. Running the project, we will get the following result: (Our default project is the Android project).


Xamarin

Summary

Finally, we have learned how use ListView Footer and Header to display data from our ViewModel at the beginning and the end of the ListView.

Up Next
    Ebook Download
    View all
    Learn
    View all