WebAppers

/ best free open source web resources /

Graphic Resources

Adding WinJS Controls to a Windows Store App

Posted · Category: Information

The Windows Library for JavaScript provides a set of new controls designed for Windows Store apps using JavaScript, such as the WinJS.UI.DatePicker, WinJS.UI.FlipView, WinjS.UI.ListView, and WinJS.UI.Rating controls. It also includes two style sheets (one with a dark color scheme and one with a light) that give your app the look and feel of Windows 8.

Prerequisites

What is the Windows Library for JavaScript?

The Windows Library for JavaScript is a library of CSS and JavaScript files. It contains JavaScript objects, organized into namespaces, designed to make developing Windows Store app using JavaScript easier. Windows Library for JavaScript includes objects that help you handle activation, access storage, and define your own classes and namespaces. It also includes a set of controls:

Control Description

AppBar Displays commands.

DatePicker Enables the user to select a date.

FlipView Displays a collection of items, one item at a time.

Flyout Displays a message that requires user interaction. (Unlike a dialog box, a Flyout doesn’t create a separate window.)

ListView Displays a collection of items in a grid or list layout.

HtmlControl Displays an HTML page.

Menu A menu flyout for displaying commands.

PageControl A set of HTML, JavaScript, and CSS that describes a page. You can navigate to a PageControl or use it like a custom control.

Rating Lets the user rate an item.

SemanticZoom Lets the user to zoom between two different views supplied by two child controls. One child control supplies the zoomed-out view and the other provides the zoomed-in view.

SettingsFlyout Provides users with fast, in-context access to app settings.

TimePicker Enables the user to select a time.

ToggleSwitch Turns an item on or off.

Tooltip Displays a tooltip that can support rich content (such as images and formatted text) to show more info about an object.

ViewBox Scales a single child element to fill the available space without resizing it. The control reacts to changes in the size of the container, and to changes in size of the child element. For example, this control responds if a media query results in a change in aspect ratio.

(For the complete list of controls, see the Controls list.)

Windows Library for JavaScript also provides styling features in the form of CSS styles and classes that you can use or override. (Control styling is described in Quickstart: styling controls.)

Adding the Windows Library for JavaScript to your page

To use Windows Library for JavaScript, your app must contain the Windows Library for JavaScript files and each page that uses Windows Library for JavaScript features must have the proper CSS and script references.

<!-- WinJS style sheets (include one) -->

<link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet">

<link href="//Microsoft.WinJS.1.0/css/ui-light.css" rel="stylesheet">

<!-- WinJS code -->

<script src="//Microsoft.WinJS.1.0/js/base.js"></script>

<script src="//Microsoft.WinJS.1.0/js/ui.js"></script>

When you use Microsoft Visual Studio Express 2012 for Windows 8 to create a Windows Store app using JavaScript, it automatically includes the files you need. This example shows the default.html page for a project that uses the Blank App template.

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>Adding WinJS controls and styles</title>

<!-- WinJS references -->

<link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet">

<script src="//Microsoft.WinJS.1.0/js/base.js"></script>

<script src="//Microsoft.WinJS.1.0/js/ui.js"></script>

<!-- AddingWinJSControlsAndStyles references -->

<link href="/css/default.css" rel="stylesheet">

<script src="/js/default.js"></script>

</head>

<body>

<p>Content goes here</p>

</body>

</html>

Adding a WinJS control in markup

Unlike HTML controls, Windows Library for JavaScript controls don’t have dedicated markup elements: you can’t create a Rating control by adding a element, for example. To add a Windows Library for JavaScript control, you create a div element and use the data-win-control attribute to specify the type of control you want. To add a Rating control, you set the attribute to “WinJS.UI.Rating”.

You must also call the WinJS.UI.processAll function in your JavaScript code. WinJS.UI.processAll parses your markup and instantiates any Windows Library for JavaScript controls it finds.

The next set of examples show you how to add a Windows Library for JavaScript control to a project created with the Blank Application template. It’s easier to follow along if you create a new Blank Application project.

To create a new project using the Blank Application template

  1. 1. Launch Visual Studio Express 2012 for Windows 8.
  2. 2. From the Start Page tab, click New Project. The New Project dialog box opens.
  3. 3. In the Installed pane, expand JavaScript and click the Windows Store app template type. The available project templates for JavaScript are displayed in the center pane of the dialog box.
  4. 4. In the center pane, pick the Blank Application project template.
  5. 5. In the Name text box, enter a name for your project.
  6. 6. Click OK to create the project. This will take a moment.

To add a WinJS control

  • 1. Create a div element where you want to place the control. Set its data-win-control attribute to the fully qualified name of the control you want to create. This example creates a Rating control on the app’s start page (the default.html file).
<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>Adding WinJS controls and styles</title>

<!-- WinJS references -->

<link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet">

<script src="//Microsoft.WinJS.1.0/js/base.js"></script>

<script src="//Microsoft.WinJS.1.0/js/ui.js"></script>

<!-- AddingWinJSControlsAndStyles references -->

<link href="/css/default.css" rel="stylesheet">

<script src="/js/default.js"></script>

</head>

<body>

<p>Create a WinJS control in markup</p>

<div id="ratingControlHost" data-win-control="WinJS.UI.Rating">

</div>

</body>

</html>
  • 1. Create a div element where you want to place the control. Set its data-win-control attribute to the fully qualified name of the control you want to create. This example creates a Rating control on the app’s start page (the default.html file).
(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());

}

};

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().

};

app.start();

})();

If you aren’t using the Blank Application template or if you’re adding the control to a page that you created yourself, you might need to add a call to WinJS.UI.processAll.

  • If you added the control to your app’s home page (which is usually the default.html file), add a call to WinJS.UI.processAll in your onactivated event handler, as shown in the previous example.
  • If you added the control to a Page control, you don’t need to add a call to WinJS.UI.processAll because the Page control does that for you automatically.
  • If you added the control to another page that is not your app’s home page, handle the DOMContentLoaded event and use the handler to call WinJS.UI.processAll.
function initialize() {

WinJS.UI.processAll();

}

document.addEventListener("DOMContentLoaded", initialize(), false);

The WinJS.UI.processAll function processes the document and activates any Windows Library for JavaScript controls that you’ve declared in markup. When you run the app, the Rating control appears where you positioned the div host element.

Setting the properties of a WinJS control in markup

When you create an HTML control, you can set its properties using dedicated attributes. For example, to set the type, min, and max properties of an input control, you can set the type, min, and max attributes in your markup:

<input type="range" min="0" max="20" />

Unlike HTML controls, Windows Library for JavaScript controls don’t have dedicated element or attribute tags; for example, you couldn’t create a Rating control and set its properties using this markup:

<!-- Not valid markup. -->

<rating maxRating="10" averageRating="6" />

Instead, you use the data-win-options attribute to set a property in markup. It takes a string that contains one or more property/value pairs:

data-win-options="{propertyName: propertyValue}"

This example sets the maxRating of a Rating control to 10.

<div id="ratingControlHost" data-win-control="WinJS.UI.Rating"

data-win-options="{maxRating: 10}">

</div>

When you run the app, the Rating control looks like this:

To set more than one property, separate them with a comma:

data-win-options="property1Name: property1Value, property2Name: property2Value"

The next example sets two properties of the Rating control.

<div id="ratingControlHost" data-win-control="WinJS.UI.Rating"

data-win-options="{maxRating: 10, averageRating: 6}">

</div>

When you run the app, the Rating control now looks like this:

If the property value is itself a string, enclose it in a different type of quote (‘ or “) than you used to set the data-win-options attribute. This example shows how to set the TimePicker control’s current property, which takes a string:

<div id="timepicker" data-win-control="WinJS.UI.TimePicker"

data-win-options="{current: '10:29 am'}">

</div>

To find out if a property is supported by a given Windows Library for JavaScript control, see its reference page.

Retrieving a control that you created in markup

You can also set the properties of a Windows Library for JavaScript control programmatically. To access the control in code, retrieve the host element and then use its winControl property to retrieve the control. In the previous examples, the host element of the Rating control is “ratingControlHost”.

var control = document.getElementById("ratingControlHost").winControl;

In some cases, you might want to retrieve and manipulate the control as soon as it’s available. Be aware that the WinJS.UI.processAll method is asynchronous, so any code that follows it might run before WinJS.UI.processAll has completed. Given this, don’t immediately try to manipulate the control because it might not be available :

WinJS.UI.processAll();

// Don't do this:

var control = document.getElementById("ratingControlHost").winControl;

control.averageRating = 3;

The WinJS.UI.processAll returns a WinJS.Promise object that you can use to call a function when the WinJS.UI.processAll method completes. Here the example defines a completion function that retrieves the control and sets its averageRating to 3.

// Do this instead:

WinJS.UI.processAll().then(function () {

var control = document.getElementById("ratingControlHost").winControl;

control.averageRating = 3;

});

The next section describes how to add event listeners to a Windows Library for JavaScript control.

Handling events for WinJS controls

Just like with HTML controls, the preferred way to attach event listeners for a Windows Library for JavaScript control is to use the addEventListener function. Retrieving a Windows Library for JavaScript control is a bit different than retrieving an HTML control, however.

To handle an event:

  1. In your JavaScript, retrieve the control’s host element and use its winControl property to retrieve the control.
  2. Call the control’s addEventListener function and specify an event and an event handler.

The next example shows how to handle the change event of a Rating control.

To handle the change event of a rating control

  • 1. In your HTML file, add a paragraph and give it an ID of “outputParagraph”. Your event listener will output to this paragraph.
<p>Create a WinJS control in markup</p>

<div id="ratingControlHost" data-win-control="WinJS.UI.Rating"

data-win-options="{maxRating: 10, averageRating: 6}">

</div>

<!-- This paragraph will be used to demonstrate event handling. -->

<p id="outputParagraph"></p>
  • 2. In your JavaScript, create an event handler function called ratingChanged that takes one parameter. This next example creates an event handler that displays the properties and values contained by the event object.
function ratingChanged(event) {

var outputParagraph = document.getElementById("outputParagraph");

var output = event.type + ": <ul>";

var property;

for (property in event) {

output += "<li>" + property + ": " + event[property] + "</li>";

}

outputParagraph.innerHTML = output + "</ul>";

}
  • 3. Use the winControl property to retrieve the control from its host element and call the addEventListener function to add your event handler. This example retrieves the control as soon as it’s created and adds the event handler:
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().then(function () {

var control = document.getElementById("ratingControlHost").winControl;

control.addEventListener("change", ratingChanged, false);

}));

}

};

When you run the app and change the rating, it creates a list of event information properties and values.

Adding a WinJS control in code

The previous examples showed you how to create and manipulate a Windows Library for JavaScript control that you created in your markup, but you can also create a Windows Library for JavaScript control using JavaScript code instead.

To create a WinJS control in code

1. In your markup, create the element that will host your control.

<div id="hostElement"></div>

2. In your code (preferably in your DOMContentLoaded event handler), retrieve the host element.

var hostElement = document.getElementById("hostElement");

3. Create your control by calling its constructor and passing the host element to the constructor. This example creates a Rating control:

var ratingControl = new WinJS.UI.Rating(hostElement);

When you run the program, it displays the Rating you created:

There’s no need to call WinJS.UI.processAll—you only need to call WinJS.UI.processAll when you create a Windows Library for JavaScript control in markup.

Summary and next steps

We’ve seen how to create Windows Library for JavaScript controls, how to set their properties, and how to attach event handlers. The next topic, Quickstart: styling controls, describes how to use Cascading Style Sheets (CSS) and the enhanced styling capabilities of Windows Store apps using JavaScript. To learn more about specific controls, see the Controls list and Controls by function topics.

Sample

DatePicker and TimePicker sample
Demonstrates the DatePicker and TimePicker controls.

Getting started with the ListView sample
Demonstrates the WinJS.UI.ListView control, a control that displays data in a customizable list or grid.

Rating control sample
Demonstrates the WinJS.UI.Rating control.

ToggleSwitch control sample
Demonstrates the WinJS.UI.ToggleSwitch control.

Tooltip control sample
Demonstrates the WinJS.UI.Rating control.

This tutorial is brought to you by the team at MSDN. To learn more about coding for Windows Store apps, please visit http://dev.windows.com

2 Comments
Supported By

Deals

Web Browsers Icon Set
Food Icon Set
Flat Icon Set

Flat Icon Set

100 icons