Live Tiles in XAML based Windows 8 Metro Application

In this post we will discuss Live Tiles in XAML based Windows 8 Metro Application. We will see

  • Updating Live Tiles
  • Creating queue of information to update Live Tiles

What is Live Tile?

Tiles are the entry point for the application. You will find TILES for all applications installed on your machine at the start screen. These Tiles are termed as Live if we update the content of the Tiles on basis of some business rules. So when user sees the Tiles, She gets some vital information from the application. Below are the Tiles of some of the installed applications on my system.

 If you see weather application there is weather information about Seattle on the tiles itself. So to know weather information of Seattle, you do not need to open the application. You can get information by just seeing the Tile of the weather application. This information is live and will change as the weather of Seattle will be changed.

You can update information on Tiles in Four ways

  1. From Push Notification Service
  2. Locally
  3. Scheduled
  4. Periodic

In this post we are focusing on updating Tiles locally. To start with add below namespaces

image

You can update Tile using below line of code.

image

You can see that Update method takes TileNotification as input parameter. You need to pass content to update on Tile as XML to TileNotification. Tile XML can be created using below code.

image

There are many templates type available for TileTemplate. We are using TileWideText01 type (see 1st highlighted text).

There are 44 TileTemplateType available. You need to choose one as your requirement. In following post I will go in details of each TileTemplateType.

Each Tile Template Type is a XML document. We can update a particular element by selecting element with the tag name. We are doing this in second line of code. In last line we are setting the information we want to update on the Tile. You can set is dynamically according to your business requirement.

So putting all pieces of codes together on a click event of a Button, a Tile can be updated as following.


private void btnSendLiveTiles_Click_1(object sender, RoutedEventArgs e)
{
XmlDocument tileXml = TileUpdateManager.
GetTemplateContent
(TileTemplateType.TileWideText01);

XmlElement textElement = (XmlElement)tileXml.
GetElementsByTagName("text")[0];
textElement.AppendChild(
tileXml.CreateTextNode
("Hey This my Text Updated on Tile"));

TileUpdateManager.CreateTileUpdaterForApplication()
.Update(new TileNotification(tileXml));
}

Before you run and see that whether Tiles has been updated or not. You need to set Wide Logo of the application. Text on live Tiles appears only when you have set the Wide Logo. Wide Logo need to be 310×150 Pixels. To set Wide Logo from solution explorer click on Package.appmanifest file and the set the Wide Logo.

image

I have set green rectangle of size 310×150 as Wide Logo. Now go ahead and run the application. After clicking on the button close the application and go to start screen. On start screen you can see that Tile text has been updated with the text we provided.

image

You can update Tile multiple times. For that you need to enable notification queue and you can have five information in the queue to be updated on the Tile. If there are more than five information available then recent five would be updated.

image

On click event of a button you can update Tiles with three different information as following.


private void btnSendLiveTiles_Click_1(object sender, RoutedEventArgs e)
{

TileUpdateManager.
CreateTileUpdaterForApplication().
EnableNotificationQueue(true);

XmlDocument tileXml = TileUpdateManager.
GetTemplateContent
(TileTemplateType.TileWideText01);
XmlElement textElement = (XmlElement)tileXml.
GetElementsByTagName("text")[0];
textElement.AppendChild(
tileXml.CreateTextNode
("Updating Tile1"));

TileUpdateManager.CreateTileUpdaterForApplication()
.Update(new TileNotification(tileXml));

XmlDocument tileXml1 = TileUpdateManager.
GetTemplateContent
(TileTemplateType.TileWideText01);

XmlElement textElement1 = (XmlElement)tileXml1.
GetElementsByTagName("text")[0];
textElement1.AppendChild(
tileXml1.CreateTextNode
("Updating Tile2"));

TileUpdateManager.CreateTileUpdaterForApplication()
.Update(new TileNotification(tileXml1));

XmlDocument tileXml2 = TileUpdateManager.
GetTemplateContent
(TileTemplateType.TileWideText01);

XmlElement textElement2 = (XmlElement)tileXml2.
GetElementsByTagName("text")[0];
textElement2.AppendChild(
tileXml2.CreateTextNode
("Updating Tile3"));

TileUpdateManager.CreateTileUpdaterForApplication()
.Update(new TileNotification(tileXml2));
}

You can have three information in queue getting updated on Tiles. In this way you can work with Live Tiles in XAML based window8 metro application. I hope this post is useful. Thanks for reading.

ListView Binding with Grouping and Semantic Zoom in Windows 8 JavaScript Metro Application

Windows 8 CP and VS11 are around. Recently I wrote Setting up Visual Studio11 Beta for Metro Application Creation . In this post let us get into some development.

In this post we will see

  • Creating DataSource
  • ListView Binding to DataSource
  • Creating ItemTemplate
  • Grouping Data Source
  • Using SemanticZoomView over ListView

At the end of the post we will have output like below,

clip_image002clip_image004

We are going to display list of movies in a ListView. Movies will be grouped with the first letter of their title. Later in the post we will apply SemanticZoomView on the ListView . In above image you can see Semantic Zoom View. To switch between SemanticZoomView and detail view either you can tap on the screen or press CTRL + Arrow key on the keyboard.

Create DataSource

Very first we need to create a DataSource. To create DataSource right click on JS folder and add a new JavaScript file. Let us call this newly added JavaScript file as moviedata.js

clip_image002[5]

Inside newly created file, we need to create an anonymous JavaScript function and define a JavaScript array. This array contains locally data to be bind to the ListView.

MovieArray contains two properties,

  • Title to display name of the movie
  • Picture to display thumbnail of the movie.

All the movie images are inside images folder in the project. Let us create array with sample data. Array is given below.


var movieArray = [
{ title: "The Artist", picture: "images/TheArtist.jpg" },
{ title: "A Better Life", picture: "images/abetterlife.jpg" },
{ title: "Abduction", picture: "images/abduction.jpg" },
{ title: "African Cats", picture: "images/africancats.jpg" },
{ title: "Angel Crest", picture: "images/angelscrest.jpg" },
{ title: "Arthur", picture: "images/arthur.jpg" },
{ title: "Anonymous", picture: "images/anonymous.jpg" },
{ title: "A Dangerous Method", picture: "images/adangerousmethod.jpg" },
{ title: "A Good Old Fashioned Orgy ", picture: "images/agoodoldfashionedorgy.jpg" },
{ title: "A Seperation ", picture: "images/aseparation.jpg" },
{ title: "Another Earth ", picture: "images/anotherearth.jpg" },
{ title: "A Heartbeat Away ", picture: "images/aheartbeataway.jpg" },
{ title: "Bad Teacher ", picture: "images/badteacher.jpg" },
{ title: "Begineers ", picture: "images/beginners.jpg" },
{ title: "Brotherhood ", picture: "images/brotherhood.jpg" },
{ title: "Bridesmaids ", picture: "images/bridesmaids.jpg" },
{ title: "Born To Be Wild ", picture: "images/borntobewild.jpg" },
{ title: "Blackthorn ", picture: "images/blackthorn.jpg" },
{ title: "Bellflower ", picture: "images/bellflower.jpg" },
{ title: "Butter ", picture: "images/butter.jpg" },
{ title: "Bunraku ", picture: "images/bunraku.jpg" },
{ title: "Cars 2 ", picture: "images/cars2.jpg" },
{ title: "Cost Of A Soul", picture: "images/costofasoul.jpg" },
{ title: "Carnage ", picture: "images/carnage.jpg" },
{ title: "Crazy Stupid Love ", picture: "images/crazystupidlove.jpg" },
{ title: "Cracks ", picture: "images/cracks.jpg" },
{ title: "Colombiana ", picture: "images/colombiana.jpg" },
{ title: "Cedar Rapids ", picture: "images/cedarrapids.jpg" },
{ title: "Captain America ", picture: "images/captainamerica.jpg" },
];

Next we need to convert JavaScript array into list to be bind to ListView.

image

Now to make this data publicly available we need to make a namespace and on the HTML page need to add reference of this namespace to use data from this file. Namespace can be created as below,

clip_image002[7]

There are few points worth discussing about creating namespace

  • MovieData.itemList is the public member.
  • MovieData.itemList.datasource will be the datasource.

By this step we have created DataSource. And putting all piece of code together moviedata.js file will be as below,

Moviedata.js


(function () {
"use strict";
// http://www.allmoviephoto.com/photo/index_2011.html
var movieArray = [
{ title: "The Artist", picture: "images/TheArtist.jpg" },
{ title: "A Better Life", picture: "images/abetterlife.jpg" },
{ title: "Abduction", picture: "images/abduction.jpg" },
{ title: "African Cats", picture: "images/africancats.jpg" },
{ title: "Angel Crest", picture: "images/angelscrest.jpg" },
{ title: "Arthur", picture: "images/arthur.jpg" },
{ title: "Anonymous", picture: "images/anonymous.jpg" },
{ title: "A Dangerous Method", picture: "images/adangerousmethod.jpg" },
{ title: "A Good Old Fashioned Orgy ", picture: "images/agoodoldfashionedorgy.jpg" },
{ title: "A Seperation ", picture: "images/aseparation.jpg" },
{ title: "Another Earth ", picture: "images/anotherearth.jpg" },
{ title: "A Heartbeat Away ", picture: "images/aheartbeataway.jpg" },
{ title: "Bad Teacher ", picture: "images/badteacher.jpg" },
{ title: "Begineers ", picture: "images/beginners.jpg" },
{ title: "Brotherhood ", picture: "images/brotherhood.jpg" },
{ title: "Bridesmaids ", picture: "images/bridesmaids.jpg" },
{ title: "Born To Be Wild ", picture: "images/borntobewild.jpg" },
{ title: "Blackthorn ", picture: "images/blackthorn.jpg" },
{ title: "Bellflower ", picture: "images/bellflower.jpg" },
{ title: "Butter ", picture: "images/butter.jpg" },
{ title: "Bunraku ", picture: "images/bunraku.jpg" },
{ title: "Cars 2 ", picture: "images/cars2.jpg" },
{ title: "Cost Of A Soul", picture: "images/costofasoul.jpg" },
{ title: "Carnage ", picture: "images/carnage.jpg" },
{ title: "Crazy Stupid Love ", picture: "images/crazystupidlove.jpg" },
{ title: "Cracks ", picture: "images/cracks.jpg" },
{ title: "Colombiana ", picture: "images/colombiana.jpg" },
{ title: "Cedar Rapids ", picture: "images/cedarrapids.jpg" },
{ title: "Captain America ", picture: "images/captainamerica.jpg" },
];

var dataList = new WinJS.Binding.List(movieArray);

Creating ListView

We have created data source and ahead and create a ListView. In ListView we need to set itemDataSource to MovieData.itemList.dataSource.

image

If you remember while creating data source we have created public namespace with name MovieData . in MovieData.js file so we need to add reference as below.

image

At this point if we run the application we will get output as below. Essentially below is the same array we get as output we created as data source

image

Now we need to create a template to render movie image and name of the movie. An ItemTemplate for ListView can be created as below.

image

Inside ItemTemplate there are two controls

  1. Image control to render thumbnail of the movie
  2. Inside div rendering title of movie.

Now go ahead and set the itemTemplate of ListView as below

image

At this point if we run application we should get ListView as below,

image

You can notice automatically WinJS has added scrollbar. By this point we should have HTML file as below,

Default.html


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ListViewBinding</title>

<!-- WinJS references -->
<link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet">
<script src="//Microsoft.WinJS.0.6/js/base.js"></script>
<script src="//Microsoft.WinJS.0.6/js/ui.js"></script>

<!-- ListViewBinding references -->
<link href="/css/default.css" rel="stylesheet">
<script src="/js/default.js"></script>
<script src="/js/moviedata.js"></script>

</head>
<body>

<div id="headerTemplate" data-win-control="WinJS.Binding.Template" style="display: none">
<div>
<h1 data-win-bind="innerText: title"></h1>
</div>
</div>

<div id="moviesTemplate"
data-win-control="WinJS.Binding.Template">

<div style="width: 150px; height: 130px;">
<img src="#" style="width: 100px; height: 100px;"
data-win-bind="alt: title; src: picture" />
<div>
<h4 data-win-bind="innerText:title"></h4>
</div>
</div>

</div>

<div id="movieListView"
data-win-control="WinJS.UI.ListView"
data-win-options="{ itemDataSource :MovieData.itemList.dataSource,
itemTemplate:moviesTemplate,
layout: {type: WinJS.UI.GridLayout} }">
</div>
</body>
</html>

Customizing ListView

If we see the ListView, it is not that immersive. we can customize a ListView by overriding the CSS. Each HTML file got a corresponding CSS file associated. For example for default.html there is a css file default.css.Now let us go ahead and override ListView properties. In below CSS

  • ListView height and width is set to 600 pixels and 800 pixels respectively
  • ListView border is set to 2 Pixel
  • Margin of each item in ListView is set to 10 Pixel
  • On hover on each item color would get changed to Red.

image

We need to put above CSS in default.css . After that when we run the application, we will get ListView as below. You can notice that on mouse hover color is changing to Red.

image

Grouping of ListView Items

To group the items in ListView, we need to call CreateGrouped JavaScript function from base.js. This function is defined as below

clip_image001

we can see that it takes three parameters. Explanation of parameters are given below

clip_image002

As you see createGrouped function takes three functions as input parameter. So let us create these functions one by one.

Below function will compare the groups. This function will be groupSorter

clip_image001[6]

This function will return group of the item.

clip_image002[6]

Below function will return Title of the group. In this case items would be grouped with first letter.

clip_image001[8]

In last step we need to call above three functions to create group and make a public namespace for this that is it accessible from other files.

clip_image003

By putting all codes together in mymoviedata.js file you will have two public namespaces. You need to set MovieGroupedData as datasource of ListView to create grouped data.

MovieGroupedData.js


(function () {
"use strict";
// http://www.allmoviephoto.com/photo/index_2011.html
var movieArray = [
{ title: "The Artist", picture: "images/TheArtist.jpg" },
{ title: "A Better Life", picture: "images/abetterlife.jpg" },
{ title: "Abduction", picture: "images/abduction.jpg" },
{ title: "African Cats", picture: "images/africancats.jpg" },
{ title: "Angel Crest", picture: "images/angelscrest.jpg" },
{ title: "Arthur", picture: "images/arthur.jpg" },
{ title: "Anonymous", picture: "images/anonymous.jpg" },
{ title: "A Dangerous Method", picture: "images/adangerousmethod.jpg" },
{ title: "A Good Old Fashioned Orgy ", picture: "images/agoodoldfashionedorgy.jpg" },
{ title: "A Seperation ", picture: "images/aseparation.jpg" },
{ title: "Another Earth ", picture: "images/anotherearth.jpg" },
{ title: "A Heartbeat Away ", picture: "images/aheartbeataway.jpg" },
{ title: "Bad Teacher ", picture: "images/badteacher.jpg" },
{ title: "Begineers ", picture: "images/beginners.jpg" },
{ title: "Brotherhood ", picture: "images/brotherhood.jpg" },
{ title: "Bridesmaids ", picture: "images/bridesmaids.jpg" },
{ title: "Born To Be Wild ", picture: "images/borntobewild.jpg" },
{ title: "Blackthorn ", picture: "images/blackthorn.jpg" },
{ title: "Bellflower ", picture: "images/bellflower.jpg" },
{ title: "Butter ", picture: "images/butter.jpg" },
{ title: "Bunraku ", picture: "images/bunraku.jpg" },
{ title: "Cars 2 ", picture: "images/cars2.jpg" },
{ title: "Cost Of A Soul", picture: "images/costofasoul.jpg" },
{ title: "Carnage ", picture: "images/carnage.jpg" },
{ title: "Crazy Stupid Love ", picture: "images/crazystupidlove.jpg" },
{ title: "Cracks ", picture: "images/cracks.jpg" },
{ title: "Colombiana ", picture: "images/colombiana.jpg" },
{ title: "Cedar Rapids ", picture: "images/cedarrapids.jpg" },
{ title: "Captain America ", picture: "images/captainamerica.jpg" },
];

var dataList = new WinJS.Binding.List(movieArray);

function compareGroups(left, right) {
return left.charCodeAt(0) - right.charCodeAt(0);
}

function getGroupKey(dataItem) {
return dataItem.title.toUpperCase().charAt(0);
}

function getGroupData(dataItem) {
return {
title: dataItem.title.toUpperCase().charAt(0)
};
}

var publicMembers =
{
itemList: dataList
};
WinJS.Namespace.define("MovieData", publicMembers);

var groupedItemsList = dataList.createGrouped(getGroupKey, getGroupData, compareGroups);
WinJS.Namespace.define("MovieGroupedData",
{
groupedItemsList: groupedItemsList
});

})();

By this point we have created functions to group data .Next we need to modify ListView datasource to group ListView items. For that let us created a header template. Header template will display Title of the group. Header Template can be created in the same way of Item Template. Header template is given below

image

And we have already created Item Template as following.

image

To group items in ListView we need to create Header Template and Item Template. We have created this in previous step. Next we need to set datasource of the ListView to bind grouped items. ListView can be created as below for the grouped items

image

If we put all codes together then default.html will have following codes.

Default.html

Let us go ahead and run the application. We should be getting output as following.

clip_image002[13]

We have grouped items in ListView. Next let us add Semantic View. To add Semantic View you need to put ListView in side Semantic View control. In Semantic Zoom we will have two views of same ListView. We need to create a view for the zoom out . For zoom out Template can be created as given below.

clip_image003[4]

After creation of Template let us go ahead and create a ListView for Zoom Out view.

clip_image005[4]

ItemDataSource of zoomed ListView is same as of the zoomed in ListView. Now we need to put both ListView , Zoomed In and Zoomed out in the Semantic Zoom control. We can put ListView controls in Semantic Zoom control as below

clip_image007[4]

Now we should have default.html as following

Default.html


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ListViewBinding</title>

<!-- WinJS references -->
<link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet">
<script src="//Microsoft.WinJS.0.6/js/base.js"></script>
<script src="//Microsoft.WinJS.0.6/js/ui.js"></script>

<!-- ListViewBinding references -->
<link href="/css/default.css" rel="stylesheet">
<script src="/js/default.js"></script>
<script src="/js/moviedata.js"></script>

</head>
<body>

<div id="headerTemplate"
data-win-control="WinJS.Binding.Template"
style="display: none">
<div>
<h1 data-win-bind="innerText: title"></h1>
</div>
</div>

<div id="moviesTemplate"
data-win-control="WinJS.Binding.Template">

<div style="width: 150px; height: 130px;">
<img src="#" style="width: 100px; height: 100px;"
data-win-bind="alt: title; src: picture" />
<div>
<h4 data-win-bind="innerText:title"></h4>
</div>
</div>

</div>

<!--<div id="movieListView"
data-win-control="WinJS.UI.ListView"
data-win-options="{ itemDataSource :MovieData.itemList.dataSource,
itemTemplate:moviesTemplate,
layout: {type: WinJS.UI.GridLayout} }">
</div>  -->

<h1>Rate Movies Application</h1>

<div id="movieListView"
data-win-control="WinJS.UI.ListView"
data-win-options="{ itemDataSource : MovieGroupedData.groupedItemsList.dataSource,
groupDataSource: MovieGroupedData.groupedItemsList.groups.dataSource,
itemTemplate: moviesTemplate,
groupHeaderTemplate: headerTemplate,
layout: {type: WinJS.UI.GridLayout} }">
</div>
</body>
</html>

Next we need to add some CSS to make it more immersive. In default.css , we need to add below css


.win-listview
{
height: 600px;
width: 800px;
border: 2px solid gray;
}

.win-listview .win-container {
margin: 10px;
}
.win-listview .win-container:hover {
background-color: red;
border-color: red;
}
.semanticZoomItem
{
width: 130px;
height: 130px;
background-color: rgba(38, 160, 218, 1.0);
}

.semanticZoomItem .semanticZoomItem-Text
{
padding: 10px;
line-height: 150px;
white-space: nowrap;
color: white;
}

On running we should be getting the below output

clip_image002[15]

On tapping or pressing of crtl and arrow key you should be getting the semantic zoom view. Semantic Zoom View of ListView is as following image.

image

In this way we can work ListView and SemanticZoom WinJS controls. In further post we will try to pull data from service. I hope this post is useful. Thanks for reading.

Flyout control in Windows 8 HTML JavaScript Metro Application

In this post, I will discuss how to work with Flyout in Windows 8 Metro application. Flyout is a type of UI surface in Windows 8 metro application. It is used to show simple message or popup. If user touches or clicks anywhere on the screen then Flyout disappears. It usually used to collect simple user information or show some message. Flyout should be as simple as possible. It should not have complex UI. A usual flyout can be like below,

image

Flyout can be created deceptively as below.

clip_image002

Inside Flyout we can put any HTML elements. As purpose of this post I am going to put sports as option and user can select out of that options. After putting sports options Flyout div will get modified as below,

clip_image004

User can select sports from above Flyout. As the design of the page, we have put a button and output div. We are going to popup a fly out on click event of a button. On selection of a sports option in Flyout, we will display that in output div and Flyout will disappear.

Default.html


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>WinWebApp1todelete</title>
<!-- WinJS references -->
<link rel="stylesheet" href="/winjs/css/ui-dark.css" />
<script src="/winjs/js/base.js"></script>
<script src="/winjs/js/ui.js"></script>
<script src="/winjs/js/binding.js"></script>
<script src="/winjs/js/controls.js"></script>
<script src="/winjs/js/animations.js"></script>
<script src="/winjs/js/uicollections.js"></script>
<script src="/winjs/js/wwaapp.js"></script>
<link rel="stylesheet" href="/css/default.css" />
<script src="/js/default.js"></script>
</head>
<body>
<button id="butonchooseSports" type="button"
style="margin-left:900px;
margin-top:20px;font-size:x-large">
Choose Sports
</button>
<div id="sportsFlyout" data-win-control="WinJS.UI.Flyout" aria-label="{Format text flyout}">
<label for="scenario3TextColor">choose sports</label>
<br />
<select id="scenario3TextColor">
<option value="cricket">Cricket</option>
<option value="football">FootBall</option>
<option value="hocky">Hocky</option>
<option value="tenis">Tenis</option>
<option value="rugby">Rugby</option>
<option value="golf">Golf</option>
</select>
</div>
<div style="margin-left:900px;
margin-top:300px;font-size:x-large" id="outputDiv"></div>
</body>
</html>

In code behind on click event of the button Flyout can be shown as below function.

clip_image002[8]

Here we are,

  • Selecting Flyout div as win control.
  • Calling Show function to display Flyout.
  • There are input parameters of Show function. First parameter is id of button. On click event of this input button Flyout will get displayed.
  • Second parameter is position of the Flyout. Other possible value of this parameter could be top.

We are putting all code together as below,

Default.js


(function () {
'use strict';
// Uncomment the following line to enable first chance exceptions.
// Debug.enableFirstChanceException(true);
var choosesportsbutton;
WinJS.Application.onmainwindowactivated = function (e) {
if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
// TODO: startup code here

WinJS.UI.processAll().then(function () {
choosesportsbutton = document.getElementById("butonchooseSports");
choosesportsbutton.addEventListener('click', showflyout);



});
}

function showflyout()
{
var flyOut = document.getElementById("sportsFlyout").winControl;
flyOut.addEventListener('change', ChangedSportsValue);
flyOut.show(choosesportsbutton, "bottom");
}

function ChangedSportsValue(e) {

var res = document.getElementById('scenario3TextColor').value;
document.getElementById('outputDiv').innerText = "You have selected " + res;
}
}

WinJS.Application.start();
})();


In above code we are,

  • Displaying Flyout
  • Attaching change event on sports option list. In this post Id of Sports option in Flyout div is seenario3TextColor
  • Attaching click event to button and on click showing Flyout.
  • Displaying selected sports in output div

If you run, on the click event of button you should get Flyout to choose the sports as below,

image

I hope this post is useful. Thanks for reading

 

List View Data Binding in Windows 8 JavaScript Metro Application

In this post we will see,

  1. Working with ListView control in WinJS
  2. ItemTemplte in WinJS
  3. Data Binding to ListView
  4. Creating Data Source in WinJS

For purpose of this post I am going to bind name and images of Indian cricket player in ListView. After data binding ListView should look like below,

image

To bind data with ListView you need to follow certain steps.

  1. Create a Data Source
  2. Create ItemTemplate and bind data source properties to Html elements of ItemTemplate
  3. Create ListView and attach ItemTemplate to ListView
  4. Set the DataSource of ListView

Create Data Source

Let us create data to bind to the List View. I have given name of the array as PlayerData. This contains two objects Name and Photo.


var PlayerData = [
{ Name: 'Sachin Tendulkar', Photo: 'images/ST.jpg' },
{ Name: 'Mahender Singh Dhoni', Photo: 'images/MSD.jpg' },
{ Name: 'Saurabh Ganguli', Photo: 'images/SG.jpg' },
{ Name: 'Harbhajan Singh', Photo: 'images/HS.jpg' },
{ Name: 'Youvrah Singh', Photo: 'images/YS.jpg' },
{ Name: 'VVS Laxman', Photo: 'images/VVS.jpg' },
{ Name: 'Virendar Shewag', Photo: 'images/VS.jpg' },
{ Name: 'Zaheer Khan', Photo: 'images/ZK.jpg' },
{ Name: 'Sachin Tendulkar', Photo: 'images/ST.jpg' },
{ Name: 'Mahender Singh Dhoni', Photo: 'images/MSD.jpg' },
{ Name: 'Saurabh Ganguli', Photo: 'images/SG.jpg' },
{ Name: 'Harbhajan Singh', Photo: 'images/HS.jpg' },
{ Name: 'Youvrah Singh', Photo: 'images/YS.jpg' },
{ Name: 'VVS Laxman', Photo: 'images/VVS.jpg' },
{ Name: 'Virendar Shewag', Photo: 'images/VS.jpg' },
{ Name: 'Zaheer Khan', Photo: 'images/ZK.jpg' }
];

To create Data Source, I have put all the images of players in image folder. In real time applications, data must be downloaded from the Service.

Create Item Template

We need to create ItemTemplate to bind with the ListView. There are few points you need to keep in mind while creating ItemTemplate

  • ItemTemplate is a div
  • To convert div as ItemTemplate div need to have attribute data-win-control set to WinJS.Binding.Template
  • Other HTML elements should be inside the template div tag.
  • Data-win-bind is used to bind data to HTML elements.

Below I have put one div to bind name of the player and image to bind image of the player.

image

Create ListView

Data has been created. ItemTemplate has been created. Next you need to create ListView and bind ItemTemplate to that ListView.

  • ListView is a div
  • data-win-control property of div should be set to WinJS.UI.ListView
  • data-win-options take complex values.
  • Value of itemRenderer should be set to id of the div created as ItemTemplate. In our case id of ItemTemplate div is playeritemtemplate. So value of itemRenderer should be playeritemtemplate.
  • Layout should be set.
  • Value of maximum rows can be set.

Below you can find, I have created ListView and bind it to the ItemTemplate.

image

Putting all together HTML should be as below. I have put an output div. Selected value from the ListView will be displayed in output div.

Default.html


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>DataBindingPlayer</title>
<!-- WinJS references -->
<link rel="stylesheet" href="/winjs/css/ui-dark.css" />
<script src="/winjs/js/base.js"></script>
<script src="/winjs/js/ui.js"></script>
<script src="/winjs/js/binding.js"></script>
<script src="/winjs/js/controls.js"></script>
<script src="/winjs/js/animations.js"></script>
<script src="/winjs/js/uicollections.js"></script>
<script src="/winjs/js/wwaapp.js"></script>

<!-- DataBindingPlayer references -->
<link rel="stylesheet" href="/css/default.css" />
<script src="/js/default.js"></script>
</head>
<body>
<h2>Indian Team</h2>
<br />

<div id="playeritemtemplate"
data-win-control="WinJS.Binding.Template">
<div data-win-bind="innerText:Name"
style="height:20px;">
</div>
<img data-win-bind="src:Photo"
style="width:200px;height:150px;"  />
</div>

<div id="PlayerListView"
data-win-control="WinJS.UI.ListView" style="height:185px;"
data-win-options="{itemRenderer:playeritemtemplate,layout:{type:WinJS.UI.GridLayout,maxRows:1}}" >
</div>

<br />
<div id="ouputDiv" >
<span>You Selected </span>
<span id="selectedPlayer" style="height:20px;" ></span> <br />
<img id="selectedPlayerImg" style="width:200px;height:150px;"/>
</div>
</body>
</html>

Binding Data Source to ListView

To bind ListView with data source, first you need to fetch ListView div and then simply set datasource value. Below I am fetching ListView div and then setting data source value to PlayerData. If you remember, I created PlayerData as data source in starting of this post.

image

Attaching event to ListView

As of now you have created ListView and bind data source to that. Next you may want to fetch the selected item. For that you need to attach iteminvoked event to the ListView. You can add that as below. In below SelectItem is a function and it will get called on the item selection

image

In SelectItem function you will have to fetch the value of selected item and set as value of HTML element of output div.

image

Putting all together js file will have below codes

Default.js


(function () {
'use strict';
// Uncomment the following line to enable first chance exceptions.
// Debug.enableFirstChanceException(true);


var PlayerData = [
{ Name: 'Sachin Tendulkar', Photo: 'images/ST.jpg' },
{ Name: 'Mahender Singh Dhoni', Photo: 'images/MSD.jpg' },
{ Name: 'Saurabh Ganguli', Photo: 'images/SG.jpg' },
{ Name: 'Harbhajan Singh', Photo: 'images/HS.jpg' },
{ Name: 'Youvrah Singh', Photo: 'images/YS.jpg' },
{ Name: 'VVS Laxman', Photo: 'images/VVS.jpg' },
{ Name: 'Virendar Shewag', Photo: 'images/VS.jpg' },
{ Name: 'Zaheer Khan', Photo: 'images/ZK.jpg' },
{ Name: 'Sachin Tendulkar', Photo: 'images/ST.jpg' },
{ Name: 'Mahender Singh Dhoni', Photo: 'images/MSD.jpg' },
{ Name: 'Saurabh Ganguli', Photo: 'images/SG.jpg' },
{ Name: 'Harbhajan Singh', Photo: 'images/HS.jpg' },
{ Name: 'Youvrah Singh', Photo: 'images/YS.jpg' },
{ Name: 'VVS Laxman', Photo: 'images/VVS.jpg' },
{ Name: 'Virendar Shewag', Photo: 'images/VS.jpg' },
{ Name: 'Zaheer Khan', Photo: 'images/ZK.jpg' }
];

WinJS.Application.onmainwindowactivated = function (e) {
if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
WinJS.UI.processAll().then(function () {
var PlayerList = document.getElementById('PlayerListView').winControl;
PlayerList.dataSource = PlayerData;
PlayerList.addEventListener('iteminvoked', SelectItem);
});

}
}

function SelectItem(e) {
var selectedItem = PlayerData[e.detail.itemIndex];
var selecteplayer = document.getElementById('selectedPlayer');
selecteplayer.innerText = selectedItem.Name;
var selecteplayerImg = document.getElementById('selectedPlayerImg');
selecteplayerImg.src = selectedItem.Photo;
}


WinJS.Application.start();
})();



On running you should get ListView bind with players name and image.

image

I hope this post is useful. Thanks for reading.