Let us learn about some Win JS Controls in Windows Metro using HTML, CSS and JavaScript - DAY 2

Niladri.Biswas
Posted by in Windows Metro category on for Beginner level | Points: 250 | Views : 8481 red flag

In this article we will learn about Rating Control,Flip View Control,Flyout Control,List View Control,Progress Bar Control,Tooltip object,App Bar Control.


 Download source code for Let us learn about some Win JS Controls in Windows Metro using HTML, CSS and JavaScript - DAY 2

Introduction

This is the second day of the learning series where we will learn about some of the WinJS controls which are listed as under

  1. Rating Control
  2. Flip View Control
  3. Flyout Control
  4. List View Control
  5. Progress Bar Control
  6. Tooltip object
  7. App Bar Control

1.Rating Control

Purpose:Provides an intuitive rating experience that allows users to select the number of stars that represents their rating.It comes in 3 categories : Average rating, Tentative rating and User's rating

Experiment

In this experiment we will perform a Candidate self rating system for interview process.When a candidate appears for an interview, he/she will be asked to rate themselves on a scale of 5 for a particular technology. Our small application will track that.

The final output will be

The design (default.html) will be as

<body>
    <table border="1">
        <tr>
            <td><b>SlNo.</b></td>
            <td><b>Technologies</b></td>
            <td><b>Candidate Rating</b></td>
            <td><b>Load Rating</b></td>
            <td><b>Display Rating</b></td>
        </tr>
        <tr>
            <td>1.</td>
            <td>Rate yourself in C#</td>
            <td><div id="ratingCSharp" data-win-control="WinJS.UI.Rating" /></td>
            <td><button id="btnRatingCSharp">C# Rating</button></td>
            <td><label id="lblCSharpRating"></label></td>
        </tr>
        <tr>
            <td>2.</td>
            <td>Rate yourself in Metro Style Apps</td>
            <td><div id="ratingMetroStyleApps" data-win-control="WinJS.UI.Rating" /></td>
            <td><button id="btnRatingMetroStyleApps">Metro Style Rating</button></td>
            <td><label id="lblMetroStyleApps"></label></td>
        </tr>
    </table>
</body>

The data-win-control helps to host the specified Windows Library for JavaScript control in a div control. Here we are hosting a "Rating" control

The default.js file will be as

// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
    "use strict";

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;
    WinJS.strictProcessing();

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }
            args.setPromise(WinJS.UI.processAll());

            //add event listeners for the controls
            document.getElementById("btnRatingCSharp").addEventListener("click", GetRating, false);
            document.getElementById("btnRatingMetroStyleApps").addEventListener("click", GetRating, false);

        }
    };

    app.oncheckpoint = function (args) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. You might use the
        // WinJS.Application.sessionState object, which is automatically
        // saved and restored across suspension. If you need to complete an
        // asynchronous operation before your application is suspended, call
        // args.setPromise().
    };

    function GetRating(event) {

        //get the operators i.e. button text
        var operator = event.srcElement.innerText;

        switch (operator) {
            case "C# Rating": CSharpRating(); break;//Rating for C#
            case "Metro Style Rating": MetroStyleRating(); break;//Rating for Metro Style
        }       
    }

    function CSharpRating() {

        // Retrieve the div that hosts the C# Rating control.
        var ratingControlDiv = document.getElementById("ratingCSharp");

        // Retrieve the actual Rating control.
        var ratingControl = ratingControlDiv.winControl;

        document.getElementById("lblCSharpRating").innerText = ratingControl._userRating;
    }

    function MetroStyleRating() {

        // Retrieve the div that hosts the C# Rating control.
        var ratingControlDiv = document.getElementById("ratingMetroStyleApps");

        // Retrieve the actual Rating control.
        var ratingControl = ratingControlDiv.winControl;

        document.getElementById("lblMetroStyleApps").innerText = ratingControl._userRating;
    }

    app.start();
})();

Here, depending on the technology type we are capturing the rating values being specified by the candidates.

Please visit WinJS.UI.Rating object (Windows) for more information

2.Flip View Control

Purpose:Provides a way to perform a slide show.

Experiment

Let's say that we have 4 images and we want to perform a slide show for them.In that case this kind of control will be the right choice.

Let us first look at the data source that we have created in a seperate file call "DataSource.js"

(function () {
    "use strict";

    //the data
    var listData = [
                        { name: 'Flower-1', photo: "images/1.png" },
                        { name: 'Flower-2', photo: "images/2.png" },
                        { name: 'Flower-3', photo: "images/3.png" },
                        { name: 'Flower-4', photo: "images/4.png" }
                  ];

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

    var dataMembers = { itemList: dataList };

    //namespace
    WinJS.Namespace.define("SourceData", dataMembers);
})();

Here we have created our own data source which is a JSON object.Also we have created "SourceData" as the namespace so as to call this "itemList" property where we have assigned our data source from the View prespective

Now let us look into the View (default.html)

<body>
    <div id="template" data-win-control="WinJS.Binding.Template">
       <img src="#" data-win-bind="src:photo;" />
    </div>

    <div id ="divFipViewExample" 
        data-win-control="WinJS.UI.FlipView" 
        data-win-options="{itemDataSource :SourceData.itemList.dataSource, itemTemplate:select('#template')}"
        style="height: 500px ; width: 800px"/>
</body>

Since it is a FlipView, so the "data-win-control" type is "WinJS.UI.FlipView" . In the "data-win-options", we are specifying the entire JSon collection object as the datasource.From there, we are picking up the "photo" property and binding that with the "img" control's source property.

Final output

Please visit WinJS.UI.FlipView object (Windows) for more information

3.Flyout Control

Purpose:A popup control that appears when we click on a button.

Experiment

We will perform a simple experiment where we will have a normal screen where user will enter 2 numeric value in two text boxes and a button by the name "Open Popup" will be there.When the user will click on that,then the Popup will appear.The popup will contain three textboxes out of which two will be pre-populated depending on the value user has entered from the parent screen. A button by the name "Summation" be appear upon clicking which the summation will appear on the the "Result" textbox.

Let us first see the Html Code

<body>

     <button id="btnOpenPopUp">Open Popup</button>
        <table>
                <tr>
                    <td> <span>Enter 1st number</span></td>
                    <td><input id="Text1" type="text" /></td>
                </tr>
                <tr>
                    <td> <span>Enter 2nd number</span></td>
                    <td><input id="Text2" type="text" /></td>
                </tr>
                
            </table> 

        <div id="viewFly" data-win-control="WinJS.UI.Flyout">        
            <table>
                <tr>
                    <td> <span>Enter 1st number</span></td>
                    <td><input id="txtFirstNumber" type="text" /></td>
                </tr>
                <tr>
                    <td> <span>Enter 2nd number</span></td>
                    <td><input id="txtSecondNumber" type="text" /></td>
                </tr> 
                <tr>
                    <td> <span>Result</span></td>
                    <td><input id="txtResult" type="text" /></td>
                </tr>               
            </table> 
        <button id="btnAdd">Summation</button>
    </div>

</body>

If we run this at this point, we will receive

Now let us write the function.Let us put the below code in default.js file

// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
    "use strict";

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;
    WinJS.strictProcessing();

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }
            args.setPromise(WinJS.UI.processAll());
			
            btnOpenPopUp.addEventListener('click', function () {

                //assign the value of the parent control to the Popup controls
                document.getElementById('txtFirstNumber').value = document.getElementById('Text1').value;
                document.getElementById('txtSecondNumber').value = document.getElementById('Text2').value;

                //Add event listener to the "btnAdd"
                document.getElementById('btnAdd').addEventListener('click', DoOperation, false);

                //show the Flyout div. i.e. popup
                document.getElementById('divFlyoutSample').winControl.show(btnOpenPopUp);
            });


        }
    };

    app.oncheckpoint = function (args) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. You might use the
        // WinJS.Application.sessionState object, which is automatically
        // saved and restored across suspension. If you need to complete an
        // asynchronous operation before your application is suspended, call
        // args.setPromise().
    };

    function DoOperation(event)
    {
        //placeholders
        var firstInputValue = document.getElementById('txtFirstNumber').value;
        var secondInputValue = document.getElementById('txtSecondNumber').value;       

        //display the result
        document.getElementById("txtResult").value = parseInt(firstInputValue) + parseInt(secondInputValue);       
    }
    app.start();
})();

In the parent page we have "Open Popup" button(btnOpenPopUp).First we are attaching an event handler to it.Next we are assigning the value of the Parent textbox controls to the Popup controls.Next we are attaching the event handler to the "Summation" button(btnAdd) which is present in the popup control i.e. Flyout control.And finally we are making the Flyout control visible. So once the Flyout control load, it's first two textboxes will be pre-populated with the parent textbox values.Upon clicking on the "Summation" button, the addition will happen.

4.ListView Control

Purpose:Use to display data.

Experiment

Here we will have a small data source in JSON format that we will bind to the ListViewControl.

So first the data source i.e. the content of DataSource.js file

(function () {
    "use strict";

    var sourceData = [
                        { Name: 'Joshep Joes', Age:"30", Salary:9000, pic:"images/1.png" },
                        { Name: 'Manik Dey', Age: "20", Salary: 6000, pic: "images/2.png" },
                        { Name: 'Kiran Reddy', Age: "24", Salary: 19000, pic: "images/3.png" },
                        { Name: 'Bhaskar Dey', Age: "40", Salary: 50000, pic: "images/4.png" }
    ];

    var datalist = new WinJS.Binding.List(sourceData);

    var dataMembers = { itemList: datalist };

    WinJS.Namespace.define("SourceData", dataMembers);
})();

Nothing new to explain.We have a collection of entities that has "Name", "Age" and "Salary" as attributes.This data we will bind to our ListView control.

So, now let us look into the view (i.e. default.html)

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

            <table border="1">
                <tr>
                    <td><b>Name</b></td>
                    <td><b>Age</b></td>
                    <td><b>Salary</b></td>
                     <td><b>Image</b></td>
                                        
                </tr>
                <tr>
                    <td><h4 data-win-bind="innerText: Name"></h4></td>  <!-- Displays the "Name" field. -->
                    <td><h4 data-win-bind="innerText: Age"></h4></td>  <!-- Displays the "Age" field. -->
                    <td><h4 data-win-bind="innerText: Salary"></h4></td>  <!-- Displays the "Salary" field. -->
                    <td><img src="#" style="width: 60px; height: 60px;" data-win-bind="alt: Name; src: pic" /></td> <!-- Displays the "Image" field. -->

                   
                </tr>
            </table>            
        </div>
    </div>     

    <div 
        id="basicListView" 
        style="width:250px;height:500px"
        data-win-control="WinJS.UI.ListView" 
        data-win-options="{itemDataSource :SourceData.itemList.dataSource, itemTemplate: select('#divDisplayItems'),layout : {type: WinJS.UI.ListLayout}}">
    </div>

</body>

We are making the DIV(divDisplayItems) as our item template (data-win-control="WinJS.Binding.Template") .The individual items are holding the data using

 data-win-bind="innerText: <Attribute Name>"

The output is as under

If we change the layout type to "GridLayout" e.g. layout : {type: WinJS.UI.GridLayout}, then the we will get a horizontal orientation

Please visit Adding a ListView (Windows Store apps using JavaScript and HTML) for more information

5.Progressbar Control

Purpose:Provides a visual impression about the application progress.

Type

It is of 3 types :

  1. Determinate Progress Bar
  2. Indeterminate Progress Bar
  3. Indeterminate Progress Ring

Please visit Adding progress controls (Windows Store apps using JavaScript and HTML) (Windows) for more information

6.ToolTip Element

Purpose:To display tooltip.

Experiment

In this small experiemnt, we will have a label control and whenever the user will being the mouse pointer on that, the tooltip will get display

The html code is as under

<body>
   <div data-win-control="WinJS.UI.Tooltip" data-win-options="{contentElement: divContent}">
    <label id="lblMyDetail">Find my detail</label>
</div>
<div style="display: none;">
    <!--Here is the content element. 
        It's inside a hidden container so that it's 
        invisible until the tooltip displays it. -->
    <div id="divContent">
        <div id="divImage">
            <img src="images\1.png" width="200px" height="200px" />
        </div>
        <div id="divDescription">
            <p>I am a software Engineer</p>
        </div>
    </div>
</div>
</body>

We are using "WinJS.UI.Tooltip" as the data-win-control type and we have a DIV by the name "divContent" that holds the tooltip information.This DIV (divContent) we are invoking from the main div above the label control.

Here is the output

Please visit Tooltip.contentElement property (Windows) for more information

7.Appbar control

Purpose:Represents the container control that holds app UI components for commanding and experiences.

Experiment

We will add a button (say "Previous") to the application.

The html code is as under

<body>
   <div data-win-control="WinJS.UI.AppBar" id="appbar" >    
           
        <button id="btnPrevious" data-win-control="WinJS.UI.AppBarCommand" data-win-options="{label:'Back',icon:'\uE112',tooltip:'back'}"></button>

    </div>
</body>

and the default.js file is as under

(function () {
    "use strict";

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;
    WinJS.strictProcessing();

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }
            args.setPromise(WinJS.UI.processAll());
          
            btnPrevious.addEventListener('click', NavigateEventHandler);

            document.getElementById('appbar').winControl.show();


        }
    };

    app.oncheckpoint = function (args) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. You might use the
        // WinJS.Application.sessionState object, which is automatically
        // saved and restored across suspension. If you need to complete an
        // asynchronous operation before your application is suspended, call
        // args.setPromise().
    };

    function NavigateEventHandler() {        
        //do something here
    }

    app.start();
})();

Once run, we will get the below output

References

  1. data-win-control property (Windows)

Conclusion

In this article we have seen some of the frequently use controls in Windows 8 Metro apps. We will explore more in subsequent articles.Hope Thanks for reading

Page copy protected against web site content infringement by Copyscape

About the Author

Niladri.Biswas
Full Name: Niladri Biswas
Member Level: Platinum
Member Status: Member
Member Since: 10/25/2010 11:04:24 AM
Country: India
Best Regards, Niladri Biswas
http://www.dotnetfunda.com
Technical Lead at HCL Technologies

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)