How to fetch selected item of ListView in HTML based Windows 8 Metro Application

I had tough time get the value of selected item of a ListView. So in this post I am sharing the code snippet required to fetch selected item from the ListView.

Read this article for ListView Binding with Grouping and Semantic Zoom in Windows 8 JavaScript Metro Application

I strongly suggest you to read the above article for more detail on ListView. If you continue with above article and want to get the value of selected item you can do that as below,


lstMovies = document.getElementById("movieListView").winControl;  
lstMovies.addEventListener("iteminvoked", function (e) {
                e.detail.itemPromise.then(function (invokedItem) {


                    var titleOfData = invokedItem.data.title;
                    var selecteplayerImg = invokedItem.data.picture;
                });
            }, false);


In above code snippet

  • lstMovies is name of the ListView.
  • Iteminvoked is name of the event. This event gets fire when an item in the ListView is being selected.
  • There are two data bind to the List View item. They are Title and Picture. Any data can be fetched as following snippet. invokedItem is parameter of itemPromise.

image

Title and Picture are properties of the datasource bind to the ListView.

In this way you can fetch selected item from ListView in HTML based Windows 8 Metro Application. I hope this post is useful. Thanks for reading!

Isolated Storage Helper For C# and XAML based Metro Application

This post and helper class is based on work of Jamie Thomson . I thank him lot for that.

Why to use Metro Application Isolated Storage Helper?

This helper class helps you to perform Read,Write and Delete of structured data in Isolated storage folders.

How to use this?

Download Metro Application Isolated Storage Helper from here

You have a class Student



public class Student
    {
        public string Name { get; set; }
        public int RollNumber { get; set; }
    }


You want to save object of Student then you can save it in Local Folder of isolated storage as below


Student objStudent = new Student { Name = "DJ ", RollNumber = 1 };
            var objectStorageHelper = new StorageHelper<Student>(StorageType.Local);            
            objectStorageHelper.SaveASync(objStudent,"abc");



And you can read back Student from isolated storage as below



public async void ReadData()
        {            
            var objectStorageHelper = new StorageHelper<Student>(StorageType.Local);           
            Student objStudent = await objectStorageHelper.LoadASync("abc");
            
        }


Abc is name of the file. If you want to store List<Student> then you can do that as following,



List<Student> lstStudent = new List<Student>()
                                        {new Student { Name = "DJ ", RollNumber = 1 },
                                         new Student { Name = "debugmode", RollNumber = 2 }
                                        };

            var objectStorageHelper = new StorageHelper<List<Student>>(StorageType.Local);
            objectStorageHelper.SaveASync(lstStudent, "abc");



You can read List<Student> from local folder of isolated storage as following



public async void ReadData()
        {            
            var objectStorageHelper = new StorageHelper<List<Student>>(StorageType.Local);           
            List<Student> lstStudent = await objectStorageHelper.LoadASync("abc");
            foreach (var r in lstStudent)
            {
                string n = r.Name;
            }
        }




Background

I was working with storing and retrieving structured data in Isolated Storage. While Binging I came across nicely written Generic Object Storage Helper for WinRT . This is written by Jamie Thomson . When I tried using this utility I came across an exception. I tried to store object of Student as following.


private void btnSaveData_Click_1(object sender, RoutedEventArgs e)
        {
            Student objStudent = new Student { Name = "Hary ", RollNumber = 1 };
            var objectStorageHelper = new ObjectStorageHelper<Student>(StorageType.Local);            
            objectStorageHelper.SaveASync(objStudent);
        }

But while running the program I came across exception as below,

image

After inspecting I found that library is written in Developer Preview and few API has been changed in Consumer Preview. Thankfully Jamie Thomson has put the source code on the CodePlex also. A big thank to him for the same. Rather than adding DLL and working with API, I copied and pasted code in my program and started to debug that.

First changes in API from DP to CP was that there were no TryMoveToRecycleBin in StorageDeleteOption enum

image

Now StorageDeleteOption enum contains only two values as below,

image

So I replaced above line of code as below,

image

The Second changes from DP to CP I found was removal of OpenWrite and OpenRead method from IRandomAcccessStream interface

image

Where readStream is defined as below,

image

And OpenWrite has been replaced with AsStreamForWrite

image

I have modified code to explicitly take filename as well. After these changes have been done Code was ready to be used in Consumer Preview. Updated helper class code is as following,

 



     public enum StorageType
    {
        Roaming, Local, Temporary
    }

    public class ObjectStorageHelper<T>
    {
        private ApplicationData appData = Windows.Storage.ApplicationData.Current;
        private XmlSerializer serializer;
        private StorageType storageType;

        
        public ObjectStorageHelper(StorageType StorageType)
        {
            serializer = new XmlSerializer(typeof(T));
            storageType = StorageType;
        }

        public async void DeleteASync(string FileName)
        {
            FileName = FileName + ".xml";
            try
            {
                StorageFolder folder = GetFolder(storageType);

                var file = await GetFileIfExistsAsync(folder, FileName);
                if (file != null)
                {
                    await file.DeleteAsync(StorageDeleteOption.PermanentDelete);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        public async void SaveASync(T Obj,string FileName)
        {

            FileName = FileName + ".xml";
            try
            {
                if (Obj != null)
                {
                    StorageFile file = null;
                    StorageFolder folder = GetFolder(storageType);
                    file = await folder.CreateFileAsync(FileName, CreationCollisionOption.ReplaceExisting);

                    IRandomAccessStream writeStream = await file.OpenAsync(FileAccessMode.ReadWrite);
                    Stream outStream = Task.Run(() => writeStream.AsStreamForWrite()).Result;
                    serializer.Serialize(outStream, Obj);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        public async Task<T> LoadASync(string FileName)
        {
            FileName = FileName + ".xml";
            try
            {
                StorageFile file = null;
                StorageFolder folder = GetFolder(storageType);
                file = await folder.GetFileAsync(FileName);
                IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read);
                Stream inStream = Task.Run(() => readStream.AsStreamForRead()).Result;
                return (T)serializer.Deserialize(inStream);
            }
            catch (FileNotFoundException)
            {
                //file not existing is perfectly valid so simply return the default 
                return default(T);
                //throw;
            }
            catch (Exception)
                 {
                //Unable to load contents of file
                throw;
            }
        }

        private StorageFolder GetFolder(StorageType storageType)
        {
            StorageFolder folder;
            switch (storageType)
            {
                case StorageType.Roaming:
                    folder = appData.RoamingFolder;
                    break;
                case StorageType.Local:
                    folder = appData.LocalFolder;
                    break;
                case StorageType.Temporary:
                    folder = appData.TemporaryFolder;
                    break;
                default:
                    throw new Exception(String.Format("Unknown StorageType: {0}", storageType));
            }
            return folder;
        }

        private async Task<StorageFile> GetFileIfExistsAsync(StorageFolder folder, string fileName)
        {
            try
            {
                return await folder.GetFileAsync(fileName);

            }
            catch
            {
                return null;
            }
 }
    }



In this way you can work with structured data in XAML based Metro Application for Windows 8. I hope this post is useful. Thanks for reading.

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