WinJS ListView Grouping With ListLayout

Introduction

This article demonstrates how to group and display data in a WinJs ListView control with a group header when the layout is set to ListLayout. It also demonstrates how to use item template functions efficiently and bind ListView events.

In the end, this article discusses how to display grouped data with a header when the ListView layout is set to ListLayout.

Currently ListView doesn't support grouping headers when its layout is set to ListLayout. Grouping is intended for use with GridLayout only.

Create a blank JavaScript store app

Create a blank JavaScript store app say with the name "ListLayoutGroupApp".

1_llnewapp.png

Add a new JavaScript file for data initialization

Add a new JavaScript file, say data.js, to the /js folder and add the following code:

7_llcities.png

The code above creates a basic list and groups.

8_lldatagroups.png
The code above creates a global namespace "Cities" for cities data.

The example data consists of Cities with Country and population index. Cities are grouped by Country. The ListView displays the Country as a group header and its cities.

Add a new JavaScript file for template function

Add a new JavaScript file say "CustomGroups.js" to the js folder and add the following code to it.

5_lltemplatefunction.png
6_llready.png

In the code above

  1. A custom template function is defined and is responsible for adding the necessary controls and attaching events if any. The entire group's headers and their items are treated as a single list item and are without any events, similar to that of a list item. This gives you an idea of how to use a ListView vertical list with group related data under one header.
  2. A custom listener event is added on a page ready. Its main use is to adjust a list item container's height dynamically to its children's height. This also gives you an idea of how to listen to a ListView's internal unexposed view states, like itemsLoading, etcetera.

Adding a ListView control

Open default.html and add script references to js/data.js and js/CustomGroups.js.

Add the following code inside the body:

4_lllistviewcode.png
In the code above,

the ListView control itemTemplate is set to the template function ListLayoutGroupTemplate defined in CustomGroups.js and the layout is set to WinJS.UI.ListLayout. Also ItemDataSource is set to Cities.groups (defined in data.js).

The complete solution looks as in the following:

2_llsolution.png

Output

3_lloutput.png

By default, the ListView height is set to 400px, scroll the ListView to view all the cities.

Summary

In this article, I discussed how to use ListView ListLayout to display a group's headers and their data using a template function.

Up Next
    Ebook Download
    View all
    Learn
    View all