Create the user interface - Exam Ref 70-484: Essentials of Developing Windows Store Apps Using C# (2013)

Exam Ref 70-484: Essentials of Developing Windows Store Apps Using C# (2013)

Chapter 3. Create the user interface

Windows RT (WinRT) and Windows 8 are operating systems installed on small handheld tablets to desktop PCs with large multi-touch displays. The resolution, pixel density, and aspect ratio of screens vary greatly among different hardware. Users expect a Windows Store app to adapt to various screen sizes and orientations without changing the app’s usability.

The WinRT application programming interface (API) enables developers to build Windows Store apps with dynamic user interfaces (UIs). The Canvas, StackPanel, and Grid layout controls, for example, let an app adjust to changes in screen size and orientation. App bars provide users with easy access to commands without obstructing the UI.

A well-designed Windows Store app presents data to users so they can select, zoom, and perform other operations easily. The GridView, ListView, and FlipView controls display data in a Windows Store app and can be customized through data templates. Styles can be applied based on events and property changes so that the UI is updated accordingly.

Objectives in this chapter:

§ Objective 3.1: Create layout aware apps to handle view states

§ Objective 3.2: Implement layout controls

§ Objective 3.3: Design and implement the app bar

§ Objective 3.4: Design and implement data presentation

§ Objective 3.5: Create and manage XAML styles and templates

Objective 3.1: Create layout aware apps to handle view states

A well-designed Windows Store app provides a smooth and pleasant user experience across a variety of device form factors, screen sizes, and application view states by employing a predictive behavior in the UI. Your app should look great when users view it on a tablet, on a desktop PC, or on a large high-definition screen; when they change the orientation of their device; and when they change the view state of the app.

Microsoft design guidelines specify Windows Store app layouts that help you arrange controls in the UI. The UI responds to changes in the size and orientation of the screen by raising events. You can support multiple view states in your app by applying styles to specific view states in these events. The content in your app is presented through controls embedded in views. A view responds to changes in size and orientation of the screen; application view states; user actions such as panning, zooming, scaling, and resizing; and manipulation of specific UI elements by the user.

A Windows Store app can support one or more view states in the UI. Your app receives notifications whenever the view state changes and, it can query for the current view state to help with the arrangement of controls in views for a certain layout. To support multiple view states, you should use styles for each view state, which are applied to the view whenever the view state changes.

The users of your app can change the orientation of their device to suit their convenience. For example, if your app is a news or blog reader, the user might find it convenient to hold their tablet in the portrait orientation. Therefore, it is important to consider various orientations of a device and support them in your app.

NOTE

This objective covers how to:

§ Handle view state events from ViewStateManager.

§ Choose between style patterns for different view states.

§ Set up app orientation in the manifest.

Handling view state events from ViewStateManager

In traditional desktop applications, a developer must incorporate tools for a user to change the app’s orientation and screen size. However, Windows Store apps can occupy the entire screen, so developers must also consider an app’s view state. View states, shown in Figure 3-1, represent the various modes in which a user can use an app.

An illustration showing the view states of an app and their orientation. The view states are full screen landscape, full screen portrait, fill, and snapped.

Figure 3-1. Some view states and orientations of a Windows Store app

The minimum width of a Windows Store app in full screen landscape and full screen portrait modes is related to the minimum resolution of 1024 × 768, which all apps must support. Microsoft recommends 1366 × 768 as the optimum resolution that designers and developers should target.

Windows 8 enables users to use two apps simultaneously in the screen when their device is in landscape orientation. An app can be in the snapped view state if the horizontal resolution of the screen is at least 1366 pixels. The minimum horizontal resolution of an app is 1024 pixels, the width of a snapped app is 320 pixels, and the width of the splitter separating the two apps is 22 pixels. If the horizontal resolution of the screen is less than 1366 pixels, only one app can be displayed at a time.

Width specifications for various view states are in logical pixels. Therefore, an app in the snapped state will look different on screens with the same display resolution but different physical sizes. You can test your application in the Windows Simulator for various screen sizes and resolutions, which are shown in Figure 3-2.

A screenshot of the Windows Simulator showing various screen sizes and resolutions. Six options are shown, which range from 10.6” 1024 × 768 to 27” 2560 × 1440.

Figure 3-2. Screen sizes and resolutions available in the Windows Simulator

You can also test your application in the snapped and fill view states for different screen sizes and resolutions using the Microsoft Visual Studio XAML designer. Click Device in the left tab bar, open the Display drop-down menu, and select a resolution you want to test your app with. You can test for various visual states by opening the Visual State drop-down menu and selecting an option, as shown in Figure 3-3.

A screenshot of the Visual State menu in the Visual Studio XAML designer showing the options available to test for various screen sizes and resolutions. The options range from 1366 × 768, 148 dpi, on a 10.5” screen to 2560 × 1440, 109 dpi, on a 27” screen.

Figure 3-3. The Visual State menu in the Visual Studio XAML designer

MORE INFO DPI AND LOGICAL PIXELS

You can read more about dots per inch (dpi), logical pixels, and device-independent pixels at http://msdn.microsoft.com/en-us/library/windows/desktop/ff684173(v=vs.85).aspx.

To update your app’s UI when the user changes the view state, you should subscribe to the SizeChanged or LayoutUpdated event. The SizeChanged event is fired whenever the size of the UI element to which you attached the event handler changes. The LayoutUpdated event is fired when the layout updates. Within the event handler, you should check for the static Value property of the Windows.UI.ViewManagement.ApplicationView class to obtain the current view state of the app. The value of this property is one of the members of the ApplicationViewState enumeration, described in Table 3-1.

Table 3-1. ApplicationViewState enumeration members

MEMBER

VALUE

DESCRIPTION

FullScreenLandscape

0

The app is in full screen mode, in landscape orientation, with no snapped app next to it.

Filled

1

The app is in the fill state, occupying part of the screen with another app in the snapped state.

Snapped

2

The app is in the snapped state, occupying part of the screen with another app in the fill state.

FullScreenPortrait

3

The app is in full screen mode, in portrait orientation, with no snapped app next to it.

If a Windows Store app supports all the view states, it should respond to changes in the view state by updating the layout of the UI. Windows provides the Visual State Manager (VSM) (VisualStateManager class in the Windows.UI.Xaml namespace) to help manage layouts for various view states. The VSM handles the logic of the view states and transitions for controls among these states. The VSM can be used to manage the state of pages, custom and user controls, and control templates.

You can use the VSM with any UI element that derives from the Control class, for example, the Page element. The VSM should be present at the root of the control’s template. The XAML code of a page with the VSM is as follows:

<Page>

<Grid x:Name="LayoutRoot">

<VisualStateManager.VisualStateGroups>

<VisualStateGroup x:Name="OrientationStates">

<VisualState x:Name="FullScreen" />

<VisualState x:Name="Filled" />

<VisualState x:Name="Snapped" />

<VisualState x:Name="Portrait" />

</VisualStateGroup>

</VisualStateManager.VisualStateGroups>

</Grid>

</Page>

A visual state (represented by the VisualState class) consists of XAML for the UI elements in the page for that state. For example, you can display your app’s content in a grid when it is in the fill view state in the landscape orientation, and in a list when it is in the snapped view state and portrait orientation.

In the code-behind of the page that defines the visual state groups (represented by the VisualStateGroup class and containing a group of visual states), you should implement the logic to transition between the visual states in the SizeChanged event. See Transitioning between visual states in the SizeChanged event.

TRANSITIONING BETWEEN VISUAL STATES IN THE SIZECHANGED EVENT

using Windows.UI.ViewManagement;

public sealed partial class VSMSamplePage: Page

{

public VSMSamplePage

{

this.InitializeComponent();

Window.Current.SizeChanged += OnSizeChanged;

}

// Handle the SizeChanged event

public void OnSizeChanged(object sender,

Windows.UI.Core.WindowSizeChangedEventArgs args)

{

switch (ApplicationView.Value)

{

case ApplicationViewState.Filled:

VisualStateManager.GoToState(this, "Filled", false);

break;

case ApplicationViewState.FullScreenLandscape:

VisualStateManager.GoToState(this, "FullScreen", false);

break;

case ApplicationViewState.Snapped:

VisualStateManager.GoToState(this, "Snapped", false);

break;

case ApplicationViewState.FullScreenPortrait:

VisualStateManager.GoToState(this, "Portrait", false);

break;

default:

break;

}

}

}

The GoToState method accepts a Boolean parameter that indicates whether visual transitions should be used when transitioning between states. Transitions are animations controlled by a StoryBoard object that occurs between each visual state when the state changes. A StoryBoard can contain one or more animations, which are associated with UI elements. Transitions are not used in most control templates, and the transition between various states occurs instantaneously.

If you decide to use transitions between visual states, you can define them as a combination of the start state and end state in your control’s set of visual states. Transitions are defined by the Transitions property of VisualStateGroup in XAML. The VisualTransition class represents the visual behavior when a control transitions from one visual state to another. A VisualTransition initiates a StoryBoard, which outlines the duration that animations between two visual states will run.

A VisualTransition can reference a From state only, a To state only, or both a From state and a To state. The To value references the name of a state that is the new state requested by the GoToState method. The From value references the name of the previous state. The VisualStateManagerclass uses the following logic to decide which transition to apply:

§ If a VisualTransition exists that uses a From state as the old state and the new state as To, use that transition.

§ If a VisualTransition exists that uses To state as the new state but does not specify From, use that state.

§ If a VisualTransition exists that uses the From state as the old state but does not specify To, use that state.

§ If none of the above applies, the VisualStateManager does not apply any transitions.

The GeneratedDuration property of the VisualTransition class sets the time for the transition to occur. A VisualTransition can have a StoryBoard value, a GeneratedDuration value, or both. If a VisualTransition has neither a StoryBoard value nor a GeneratedDuration value, thatVisualTransition does nothing for animations, even if the From and To values refer to states defined in the VisualStateGroup.

An implicit transition is one that does not target a specific dependency property, although it can include a GeneratedDuration value to set the duration of the animation. Implicit transitions apply to properties with a Double, Color, or Point value; that is, the property must be possible to implicitly animate with an animation of type DoubleAnimation, PointAnimation, or ColorAnimation. If you need to create a transition animation on any other value, you should put that animation in the StoryBoard and give the animation a Duration that you want it to run.

Another category of animations is transition animations. A transition animation represents a change in the relationship between a UI element and the UI. For example, with a change in the view state, you might want to move a UI element in the layout container of the page. A transition animation applies to various Transition properties of a UIElement class and its derived classes, not to a VisualStateGroup. Transition animations are usually built into the default behavior of a control. The XAML in Defining the transition for a control shows the Transitions property ofVisualStateGroup used to define the transition for a control. The first three transitions are examples of implicit transitions, and the fourth is an explicit transition that targets a specific property.

DEFINING THE TRANSITION FOR A CONTROL

<VisualStateGroup x:Name="OrientationStates">

<VisualStateGroup.Transitions>

<!-- The following three visual transitions are implicit transitions -->

<VisualTransition To="Snapped" GeneratedDuration="0:0:0.1" />

<VisualTransition To="Filled" GeneratedDuration="0:0:0.5" />

<VisualTransition From="Portrait" To="FullScreen" GeneratedDuration="0:0:0.1" />

<!-- The following visual transition is an explicit transition -->

<VisualTransition From="FullScreen" To="Portrait" GeneratedDuration="0:0:1.5">

<Storyboard>

<DoubleAnimationUsingKeyFrames

Storyboard.TargetProperty="X"

Storyboard.TargetName="TopRect"

FillBehavior="HoldEnd" >

<LinearDoubleKeyFrame Value="80" KeyTime="0:0:1" />

</DoubleAnimationUsingKeyFrames>

</Storyboard>

</VisualTransition>

</VisualStateGroup.Transitions>

<VisualState x:Name="Snapped" />

<VisualState x:Name="FullScreen" />

<VisualState x:Name="Filled">

<Storyboard>

<ColorAnimation Storyboard.TargetName="BorderBrush"

Storyboard.TargetProperty="Color" To="Green" />

</Storyboard>

</VisualState>

<VisualState x:Name="Portrait">

<Storyboard >

<ColorAnimation Storyboard.TargetName="BorderBrush"

Storyboard.TargetProperty="Color" To="Transparent"/>

</Storyboard>

</VisualState>

</VisualStateGroup>

Although you might decide to not define the snapped view state in your Windows Store app, the user can still snap your app. This can result in the addition of scrollbars in the controls of the page that is currently visible, or the UI might be partially visible. If your app requires a lot of space for the user to effectively utilize the features in your app, you can include a button that unsnaps your app. In the event handler, call the TryUnsnap method of the ApplicationView class, as follows:

Sample of C# code

using Windows.UI.ViewManagement;

// Try to unsnap the app

private void UnsnapButton_Click(object sender, RoutedEventArgs args)

{

bool unsnapped = ApplicationView.TryUnsnap();

// Check the value of unsnapped to see if the application unsnapped.

// Respond with a message if the app must unsnap.

}

Choosing between style patterns for different view states

The usability of a well-designed Windows Store app does not vary between view states although the layout can change between the various view states. You can implement your app’s UI layout based on view states, window dimensions (that is, the size of your app), a combination of view states and window dimensions, or none of them. The presentation of content in your app depends on the type of content as well as your app’s usage pattern. For example, for an app that displays news articles, tablet users might want to use portrait and landscape modes, whereas laptop or desktop PC users will use only landscape orientation.

When a device is in landscape orientation, the available area in the vertical direction is limited. The layout of UI elements is therefore constrained in the vertical direction and the elements should be laid out in the horizontal direction. When the device is in portrait orientation, the available area in the horizontal direction is limited and the layout of UI elements is horizontally constrained.

The design of the UI of your app in the snapped and fill views requires special attention. In well-designed applications, the UI in the snapped state adapts to a vertical layout with attention to vertical arrangement of content. Although the fill view state provides a fair amount of window size, important content should appear on the left side of the window to ensure that it is visible.

A Windows Store app with well-designed snapped and fill views as well as for the portrait orientation is likely to be used along with other apps. For example, a tourist planning a visit to a distant city might open the Maps app and the Weather app and use them together. Supporting all the view states in such apps allows users to regularly use them, thereby increasing the visibility of these apps.

You can use the VSM, along with the various application view states, styles, and control templates, to build Windows Store apps with adaptive layouts. The VSM defines groups that consist of mutually exclusive states and, optionally, transitions between those states. The states are mutually exclusive because the VSM allows only one state to be visible at a time. The GoToState method of the VisualStateManager initiates the transition between states. The VSM or the system does not expect you to write code that updates the layout and controls of the UI. This helps decouple the details of the UI and controls in a state and the state itself.

Visual Studio provides developers with Windows Store app templates that include support for using the VSM with an adaptive layout. An example of an app built with the Grid App template showing various view states, as shown in Figure 3-4.

Screenshots of a Windows Store app in different view states: full screen landscape, full screen portrait, fill, and snapped. The app was built with the Grid App template provided in Visual Studio.

Figure 3-4. Windows Store app in various view states; the app was built with the Grid App template provided in Visual Studio

When a Windows Store app transitions between states, styles and control templates can be applied based on the content displayed on the screen. A layout with whitespace to create a visual separation between groups of data might work in a full screen landscape or fill state; however, in the snapped state, the app needs to minimize whitespace and update the layout to use the vertical dimension. A closer view of the app prepared using the Grid App template is shown in Figure 3-5.

Screenshots of a Windows Store app built with the Grid App template in the full screen landscape state (on the left) and the snapped state (on the right).

Figure 3-5. A Windows Store app built with the Grid App template in the full screen landscape view state (left) and snapped state (right)

You can implement controls that render content in specific view states and hide the content in all other view states. Similarly, you can group the use of buttons, images, and font properties in styles that are applied for a specific visual state. In Figure 3-5, the app uses a GridView control in the full screen landscape and fill states to lay out content, and uses a ListView control to lay out the same content in the snapped view state. In this case, the visual state transitions control the visibility of these controls as well as various other properties of other controls such as font size of text blocks and size of images in an individual item of the list. The XAML of the VisualStateGroup of the page in Figure 3-5 is shown in Defining the XAML of the VisualStateGroup.

DEFINING THE XAML OF THE VISUALSTATEGROUP

<VisualStateManager.VisualStateGroups>

<VisualStateGroup x:Name="ApplicationViewStates">

<VisualState x:Name="FullScreenLandscape"/>

<VisualState x:Name="Filled"/>

<!-- The back button and title have different styles when snapped,

and the list representation is substituted for the grid

displayed in all other view states

-->

<VisualState x:Name="Snapped">

<Storyboard>

<ObjectAnimationUsingKeyFrames Storyboard.TargetName="backButton"

Storyboard.TargetProperty="Style">

<DiscreteObjectKeyFrame KeyTime="0"

Value="{StaticResource SnappedBackButtonStyle}"/>

</ObjectAnimationUsingKeyFrames>

<ObjectAnimationUsingKeyFrames Storyboard.TargetName="pageTitle"

Storyboard.TargetProperty="Style">

<DiscreteObjectKeyFrame KeyTime="0"

Value="{StaticResource SnappedPageHeaderTextStyle}"/>

</ObjectAnimationUsingKeyFrames>

<ObjectAnimationUsingKeyFrames Storyboard.TargetName="itemListView"

Storyboard.TargetProperty="Visibility">

<DiscreteObjectKeyFrame KeyTime="0" Value="Visible"/>

</ObjectAnimationUsingKeyFrames>

<ObjectAnimationUsingKeyFrames Storyboard.TargetName="itemGridView"

Storyboard.TargetProperty="Visibility">

<DiscreteObjectKeyFrame KeyTime="0" Value="Collapsed"/>

</ObjectAnimationUsingKeyFrames>

</Storyboard>

</VisualState>

</VisualStateGroup>

</VisualStateManager.VisualStateGroups>

The VSM makes it easy for developers to support multiple view states in the layout of pages without having to implement pages specifically for a view state. The project template provided by Visual Studio adds a class called LayoutAwarePage that includes code to support theVisualStateManager class along with the SizeChanged event to cater for view state changes. You should use the LayoutAwarePage class as the base class of the pages in your Windows Store apps to include support for view state changes.

Setting up app orientation in the manifest

For some Windows Store apps, it is important to restrict their visual experience to specific view states. They start in a specific orientation and are not expected to respond to any changes in the orientation. A movie player is a good example. The user can hold their device in portrait orientation, thereby making the video appear in a letter box if the movie player supports both portrait and landscape orientations.

Visual Studio provides you with the option to select the supported orientations of your app through the package manifest, shown in Figure 3-6.

A screenshot of the Application UI tab for the package manifest file in Visual Studio. The screen displays options for setting the preferred orientation: Landscape (which is selected), Portrait, Landscape-flipped, and Portrait-flipped.

Figure 3-6. Package manifest options for setting the preferred orientation

A Windows Store app that does not support portrait orientation must support the fill, snapped, and full screen view states in landscape orientation. The choice of orientations supported by the app determines the layout of the pages in the app as well as the splash screen. If an application supports the portrait orientation only, the splash screen is always shown in the portrait mode.

THOUGHT EXPERIMENT

Designing an app to support multiple screen sizes

In this thought experiment, apply what you’ve learned about this objective. You can find answers to these questions in the “Answers” section at the end of this chapter.

You have been asked to participate in a project to port a popular and successful iOS app used in the healthcare industry to Windows 8. Currently, organizations can use a companion desktop app as well as a web application to manage various parts of the business workflow. You are expected to merge all applications into a single Windows Store app that will run on tablets, laptops, and desktop PCs. The devices support multiple screen sizes and resolutions, and the Windows Store app must support them as well as all view states. Some devices use a touch interface; others provide input through a keyboard and mouse.

You have been asked to lead the app’s development and provide guidance on design principles. What are three recommendations you are likely to present to your development team?

Objective summary

§ While designing and implementing your Windows Store app, you should consider various screen sizes and resolutions of devices and PCs as well as the view states your app can be in.

§ You should use the VisualStateManager class with the VisualState class for the view states you support in your app.

§ Styles and control templates enable reuse of visual elements. They should be used with the VisualStateManager class to lay out UI elements.

§ You can provide the preferred orientations of your app through its package manifest. Note that the user can still put your app in the snapped view state even if you do not support portrait orientation. The snapped and fill view states are available only in landscape orientation.

Objective review

Answer the following questions to test your knowledge of the information in this objective. You can find the answers to these questions and explanations of why each answer choice is correct or incorrect in the “Answers” section at the end of this chapter.

1. You are developing a Windows Store app that will be used in all possible orientations and view states. You have updated the package manifest in Visual Studio to configure the supported orientations. Which view states do you need to support? (Choose all that apply.)

a. Full screen view state in the landscape orientation

b. Fill view state in the landscape orientation

c. Snapped view state in the landscape orientation

d. Snapped view state in the portrait orientation

e. Fill view state in the portrait orientation

2. You are implementing support for the snapped and fill view states in your news reader app. You want the user to be able to read a summary of each news item with its title and, if available, a thumbnail. What is the recommended way of implementing this requirement?

a. Create a VisualState for each view state. Use implicit transitions to move and resize UI elements in the layout.

b. Create a VisualState for each view state. Use explicit transitions on the properties of the UI element to arrange them in the layout.

c. Create styles and control templates for the view states. Use the VisualStateManager to switch between the view states.

d. Allow Windows to automatically add vertical and horizontal scrollbars; there is no need to add anything to support multiple view states.

3. You are porting a desktop application to a Windows Store app. Users want to use your app in any orientation they like, and they want the content to be readable in all view states. What steps should you follow to implement these requirements? (Choose all that apply.)

a. Declare the orientations your app will support in the package manifest.

b. Define visual states in the XAML of various pages in the application.

c. In the OnLaunched event of the app, examine the current value of the ApplicationViewState and use the VisualStateManager to change the layout for the view state.

d. In the OnSizeChanged event of a page, examine the current value of the ApplicationViewState and use the VisualStateManager to change the layout for the view state.

e. In the constructor of a page, examine the current value of the ApplicationViewState and use the VisualStateManager to change the layout for the view state.

Objective 3.2: Implement layout controls

The layout of a Windows Store app is an important feature that designers and developers should pay attention to. Unlike other platforms, Windows 8 screens can range from small handheld tablets to large high-definition wall-mounted displays. Users expect Windows Store apps to smoothly handle multiple screen sizes and orientations and use the available area on the screen. Microsoft provides developers with layout controls that help with the arrangement of content in a scale-free way as well as adapting to multiple view states and orientations.

A Windows Store app consists of a root UI element (called Frame) that represents the area occupied by the application on a Windows 8 PC or device. The Frame acts as a container of the content in the app and supports navigation in an app with multiple pages. (Each page is represented by the Page UI element.) A Page consists of a set of controls that provide the look and feel you decide to implement. Layout controls such as Canvas, Grid, WrapGrid, VariableSizedWrapGrid, and StackPanel make it very easy for developers to position content within their apps.

The Grid control provides a flexible yet powerful way of arranging UI elements in a page of a Windows Store app. It helps with the layout of controls in multiple rows and multiple columns, and provides a number of ways to control their height and width. Using a grid in a page is similar to using <table> elements in a HTML page to arrange items in rows and columns. You can even use a mix of fixed and proportional dimensions for rows and columns in a grid, allowing your app to adjust to variations in the screen size, resolution, and view states.

NOTE

This objective covers how to:

§ Implement the Grid control to structure the app layout.

§ Set the number of rows/columns and size.

§ Enable scroll and zoom capabilities in layout controls.

§ Manage text flow and presentation.

Implementing the Grid control to structure the app layout

The layout of Windows Store apps differs from the layout of traditional desktop apps. You have a number of options in which to place controls, such as the app window, flyouts, pop-ups, dialog boxes, and app bars. The app page forms the base surface of your app’s UI. Ideally, you should use this surface to integrate the UI elements. An error message, for example, can appear as highlighted inline text with an animation and hidden after the user has viewed it, instead of using the traditional pop-up dialog box. A Windows Store app can have as many app pages as necessary to meet business requirements and user scenarios.

In an app page, use a layout control to build its structure along with the set of controls provided by Visual Studio. The Grid control is the most commonly used control for creating layouts in Windows Store apps. Similar to a HTML table, the Grid allows you to specify a number of rows and columns and their dimensions. The size of cells in a grid are specified in pixels, as a ratio relative to the size of other cells, or to automatically resize based on the size of the cell’s contents.

Using a grid-based layout in a Windows Store app offers several benefits. A well-designed Windows Store app applies the basic Microsoft design style principles of being fast and fluid with an emphasis on content rather than UI elements such as whitespace, gradient, and color. This means your app follows a consistent pattern of page headers, margins, padding, gutter widths, and so on. A prominent feature of the grid-based layout is the silhouette, which consists of a wide margin on the top, bottom, and left edges. This provides users with a visual guide to scroll or pan the content horizontally.

Visual Studio provides a set of templates that use a grid layout to arrange controls with support for multiple view states. Figure 3-7 shows the layout of two Windows Store apps using the templates provided by Visual Studio.

Screenshots of the Visual Studio Grid App template (top) and the Split App template (bottom). A callout points to the top, left, and bottom silhouettes in each screenshot.

Figure 3-7. Layout of the Visual Studio Grid App and Split App templates

To support multiple view states, you can define visual states and styles associated with them. Visual Studio templates include support for orientation and view state changes. Figure 3-8 shows a few templates in the snapped view state.

Screenshots of the Visual Studio Grid App and Split App templates in the snapped view state.

Figure 3-8. Layouts of the Visual Studio Grid App and Split App templates in the snapped view state

The apps created using the Grid App and Split App templates in Visual Studio have some unique visual features:

§ The apps have their silhouettes clearly defined. The silhouette is visible in the snapped view state.

§ The padding between groups of data is consistent across the app, in all view states.

§ The padding between items in a group is consistent across the app, in all view states.

The consistency in the appearance of Windows Store apps using a grid to lay out pages is an incentive for users to use your app. Microsoft prepared some guidelines while designing the controls and the grid-based templates. These guidelines should be followed by Windows Store app developers whenever possible; they are summarized here:

§ The grid layout system is made up of units and subunits, the unit being the basic unit of measurement. A unit is 20 × 20 pixels square. It is divided into subunits of 5 × 5 pixels; therefore, there are 16 subunits per unit. It is a good practice to compose your UI in multiples of units and subunits.

§ The baseline of the app page header is 5 units, or 100 pixels from the top. The left margin for the page header is 6 units, or 120 pixels. The recommended font for the page header is SegoeUI Stylistic Set 20, light weight.

§ The content region has a top margin of 7 units, or 140 pixels. The left margin is 6 units, or 120 pixels. Therefore, there is a 2-unit, or 40-pixel, separation between the top of the content area and the baseline of the page header.

§ Horizontal padding between content items varies with the type of item. Items with hard edges such as images and user tiles are separated from accompanying text by 2 subunits, or 10 pixels of padding. Hard-edged items are separated by 2 units, or 40 pixels of padding. Lists in columns are separated by 2 units, or 40 pixels of padding.

§ The horizontal padding between groups of items is 4 units, or 80 pixels. Whitespace helps users distinguish between groups while panning or scrolling across many groups horizontally.

§ Vertical padding between content items varies with the type of item. Tile and text lists have 1 unit, or 20 pixels, of vertical padding between items in a row. Hard-edged items placed in rows have 2 subunits, or 10 pixels, of padding between items in a row.

MORE INFO PAGE LAYOUT AND TYPOGRAPHY GUIDELINES

Microsoft provides designers of Windows Store apps with page layout and typography guidelines. Page layout guidelines are available at http://msdn.microsoft.com/en-au/library/windows/apps/hh872191.aspx, and typography guidelines are available at http://msdn.microsoft.com/en-au/library/windows/apps/hh700394.aspx.

Using a grid layout for app pages enables automatic scaling at different screen sizes and resolutions. Larger screen sizes support a higher resolution, which can be a challenge for developers to rearrange UI elements in response to events that are raised when screen resolution is updated. The application created with the Grid App template shown in Figure 3-7 is running in a 10.6” screen at 1366 × 768 resolution. The same application is also shown in Figure 3-9, running in a 23” screen at 1920 × 1080 resolution. You will notice that the layout of the UI elements changes automatically with the screen resolution. The extra space is used to lay out more groups in the visible area of the screen.

A screenshot of a Windows Store app showing the change in the arrangement of controls when running in a 23” screen at 1920 × 1080 resolution. You will notice how the layout of the items in the application is updated automatically when the screen resolution changes (compared with the layout in ).

Figure 3-9. Change in the arrangement of controls in an app using a grid layout in a 23” screen running at 1920 × 1080 resolution

Microsoft recommends you design Windows Store apps for a minimum resolution of 1024 × 768 and an optimum resolution of 1366 × 768. Recall that in the former case, the screen size is not adequate for your app to be snapped. For large screens, the general recommendation is to fill up the available area while maintaining the guidance for the silhouette of your app.

If your app will cater to larger screens, you can implement a fixed layout in which there is a fixed amount of content, or a scale-to-fit layout to have your fixed layout fill the screens of various sizes. The scale-to-fit approach is built into the Windows 8 platform. You can place fixed content in a ViewBox control, which scales a fixed layout to fit the whole screen. The ViewBox control should be sized to 100% width and height, and its fixed size properties should be sized to the fixed pixel sizes of the layout (for example, 1366 × 768). If your app will support an adaptive layout, you should determine how your app will use the extra space available on a larger screen.

MORE INFO WINDOWS 8 USER EXPERIENCE GUIDELINES

Microsoft provides designers and developers of Windows Store apps with a handbook of user experience guidelines that can be downloaded from http://www.microsoft.com/en-au/download/details.aspx?id=30704.

Setting the number of rows/columns and size

The Grid control has a collection of rows and columns that can create various control arrangements that compose the UI. Some of the properties that are commonly specified for a Grid control are the following:

§ ColumnDefinitions. This property contains a collection of one or more ColumnDefinition objects. A ColumnDefinition object defines column-specific properties that apply to Grid elements. The Width property of ColumnDefinition specifies the width of a column in a grid.

§ RowDefinitions. This property contains a collection of one or more RowDefinition objects. A RowDefinition object defines row-specific properties that apply to Grid elements. The Height property of RowDefinition specifies the height of a row in a grid.

§ Background. This property is used to specify the Brush used as the background of the control. A brush can be a solid color or an image.

§ Height. and Width These properties control the size of the Grid control. In most design scenarios, the height and width of the Grid control is not specified and is allowed to occupy all available space in the frame.

The following XAML code shows how you can use the RowDefinitions and ColumnDefinitions properties to define a grid layout with three rows and two columns:

<Grid x:Name="PageLayoutRoot">

<Grid.ColumnDefinitions>

<ColumnDefinition />

<ColumnDefinition />

</Grid.ColumnDefinitions>

<Grid.RowDefinitions>

<RowDefinition />

<RowDefinition />

<RowDefinition />

</Grid.RowDefinitions>

</Grid>

You can place and position controls within the grid by specifying their Grid.Row and Grid.Column properties to the respective row and column of the grid. You should note that the rows and columns follow a zero-based index. For example, if you want to place a colored rectangle in the first column, second row of the control, use the following XAML code:

<Grid x:Name="PageLayoutRoot">

<Grid.ColumnDefinitions>

<ColumnDefinition />

<ColumnDefinition />

</Grid.ColumnDefinitions>

<Grid.RowDefinitions>

<RowDefinition />

<RowDefinition />

<RowDefinition />

</Grid.RowDefinitions>

<Rectangle Grid.Row="1" Grid.Column="0" Fill="Wheat" />

</Grid>

In some Windows Store apps, you might need to position a control so it occupies multiple rows or columns. You can use a combination of the RowSpan and ColumnSpan properties in the RowDefinitions and ColumnDefinitions properties for arranging controls in a grid, as follows:

<Grid x:Name="PageLayoutRoot">

<Grid.ColumnDefinitions>

<ColumnDefinition />

<ColumnDefinition />

<ColumnDefinition />

<ColumnDefinition />

<ColumnDefinition />

</Grid.ColumnDefinitions>

<Grid.RowDefinitions>

<RowDefinition />

<RowDefinition />

<RowDefinition />

<RowDefinition />

<RowDefinition />

</Grid.RowDefinitions>

<Rectangle Grid.Row="1" Grid.Column="1" Fill="LightBlue" />

<Rectangle Grid.Row="2" Grid.Column="0" Fill="DarkBlue" Grid.ColumnSpan="2" />

<Rectangle Grid.Row="3" Grid.Column="1" Fill="Tomato" Grid.RowSpan="2" />

</Grid>

Figure 3-10 illustrates how the controls are arranged in the grid layout when viewed in the Visual Studio XAML designer.

A screenshot of the Visual Studio designer showing the layout of controls in a grid. The grid has 5 rows and 5 columns. Four cells in the second column are colored: one is light blue, one is dark blue, and the last two are light red. Two cells in the third row are colored; both are dark blue.

Figure 3-10. Controls in the grid layout of a page

If you look at Figure 3-10 closely, you will notice that the Visual Studio designer has placed 1* against the rows and columns of the grid. This results from the associated XAML—the members of the RowDefinitions and ColumnDefinitions of the grid do not specify their dimensions. Therefore, the available screen area is distributed equally among all rows and columns. Although this might be adequate for arranging controls in a grid layout in many scenarios, you will sometimes require more control over the dimensions of grid rows and columns.

The Grid control supports three ways of specifying the dimensions of RowDefinition and ColumnDefinition:

§ Auto. Setting the Height or Width to Auto results in the child elements in the cells defined by the rows and columns occupying as much space as required to render. The height of a row is the height of the tallest UI element in that row, and the width of a column is the width of the widest UI element in that column.

§ Fixed Size. You can specify the width or height in logical pixels, which results in fixed sizes of the rows and columns.

§ Star Sizing. You can set the height of a row or the width of column to *. This results in the available space being distributed equally among elements or based on ratios. Note that you can use either 1* and * for star sizing a column or row in a layout.

The option of using star sizing to control column width and row height in a grid is a powerful technique for arranging elements that use available space in various screen sizes and resolutions. There are some rules you need to follow to use star sizing:

§ When you set a row’s height or column’s width to *, the row or column occupies all remaining space if the heights of other rows and widths of other columns are fixed.

§ When you set the height of multiple rows or width of multiple columns to *, the remaining space is equally divided among the rows or columns.

§ You can apply a weight to rows and columns by placing a coefficient in front of the *. The rows and columns with the applied weight occupy more space than other rows and columns. For example, a row with its height set to 3* occupies three times the height of a row with height set to *.

In your app, you might need to arrange controls so that the row or column they are placed in is a proportion of the other rows or columns. The following XAML shows the second row is twice as wide as other rows, and the fourth column is half as wide as other columns:

<Grid x:Name="PageLayoutRoot">

<Grid.ColumnDefinitions>

<ColumnDefinition />

<ColumnDefinition />

<ColumnDefinition />

<ColumnDefinition Width="0.5*"/>

<ColumnDefinition />

</Grid.ColumnDefinitions>

<Grid.RowDefinitions>

<RowDefinition />

<RowDefinition Height="2*" />

<RowDefinition />

<RowDefinition />

<RowDefinition />

</Grid.RowDefinitions>

<Rectangle Grid.Row="1" Grid.Column="1" Fill="LightBlue" />

<Rectangle Grid.Row="2" Grid.Column="0" Fill="DarkBlue" Grid.ColumnSpan="2" />

<Rectangle Grid.Row="3" Grid.Column="1" Fill="Tomato" Grid.RowSpan="2" />

<Rectangle Grid.Row="4" Grid.Column="2" Fill="ForestGreen" Grid.ColumnSpan="3" />

</Grid>

Figure 3-11 shows the XAML rendered in the Visual Studio XAML designer.

A screenshot of the Visual Studio designer showing the layout of controls in a grid with rows and columns configured with proportional width and height.

Figure 3-11. The rows and columns in a grid configured with proportional height and width

EXAM TIP

You will not be required to write XAML in the exam. However, you might be asked questions where XAML will be shown for creating layouts per the requirements of a Windows Store app. Therefore, you must understand how the Grid control is used with layout controls in an app.

Enabling scroll and zoom capabilities in layout controls

In some Windows Store apps, the amount of data to display on the screen might not be known until the user starts using the app. Data might overflow the visible area on the screen, and the user might not be able to view a lot of the data. For example, the data returned from a remote web service consists of groups of data displayed horizontally, with the items in each group displayed vertically in columns. In such a scenario, the data in the columns might not fit in the screen and will not be visible to the user.

The ScrollViewer control is available for developers to lay out UI elements so they are visible within the available screen area. It provides a virtual surface adequate for rendering all UI elements placed within it. The ScrollViewer can handle horizontal and vertical scrolling, which depend on the preferences you set when you configure it. Content placed within the ScrollViewer is displayed within the visible area of the control, called the viewport.

The following are commonly used properties of ScrollViewer:

§ Height and Width. These properties are used to specify the height and width of the viewport. If the content placed within the ScrollViewer occupies more area than that specified by the Height and Width, it will be clipped or scrollbars will be added based on their visibility settings.

§ HorizontalScrollBarVisibility. This property controls whether the ScrollViewer should display a horizontal scrollbar. The values allowed for this property are Disabled, Auto, Hidden and Visible. The default value is Disabled.

§ VerticalScrollBarVisibility. This property controls whether the ScrollViewer should display a vertical scrollbar. The values allowed for this property are Disabled, Auto, Hidden and Visible. The default value is Visible.

§ Content. This property can be used to set the content of the ScrollViewer control. The child element specified through the Content property is then scrolled using the ScrollViewer.

The HorizontalScrollBarVisibility and VerticalScrollBarVisibility properties of the ScrollViewer can be specified in the XAML of a page or its code-behind. Their values belong to the ScrollBarVisibility enumeration, as described in Table 3-2.

Table 3-2. ScrollBarVisibility enumeration members

MEMBER

VALUE

DESCRIPTION

Disabled

0

The scrollbar is not visible, and scrolling is not available for the content even when the viewport cannot display it. The content is allowed to occupy the visible area in the parent UI element.

Auto

1

The scrollbar appears when the content is large enough to require scrolling; that is, it does not fit within the viewport.

Hidden

2

The scrollbar does not appear even though the content can be scrolled and the viewport cannot display all the content. This value should be avoided in Windows Store apps because the user might not realize that the content in the ScrollViewer needs scrolling.

Visible

3

The scrollbar always appears whenever there is focus on the ScrollViewer. If the content fits within the viewport, the scrollbar will be disabled and will appear grayed-out.

The Height and Width properties can be used to explicitly specify the height and width of a ScrollViewer control. When placed in a layout within a grid, the ScrollViewer occupies the available area by default. Whenever required, you can use a ScrollViewer with scrollable content placed in a child UI element, such as a Grid or StackPanel. See the XAML code in Using a ScrollViewer with scrollable content.

USING A SCROLLVIEWER WITH SCROLLABLE CONTENT

<Page>

<Grid x:Name="PageLayoutRoot">

<Grid.RowDefitions>

<RowDefinition Height="140" />

<RowDefinition Height="*" />

</Grid.RowDefinitions>

<Grid Grid.Row="0">

<!-- Content for title-->

</Grid>

<Grid Grid.Row="1">

<Grid.RowDefinitions>

<RowDefinition Height="*" />

</Grid.RowDefinitions>

<Grid.ColumnDefinitions>

<ColumnDefinition Width="*" />

<ColumnDefinition Width="*" />

<ColumnDefinition Width="*" />

</Grid.ColumnDefinitions>

<ScrollViewer Grid.Column="0">

<StackPanel Orientation="Vertical"> <!-- Child of ScrollViewer -->

<!-- TextBlocks for the column are placed here -->

</StackPanel>

</ScrollViewer>

<ScrollViewer Grid.Column="1">

<StackPanel Orientation="Vertical"> <!-- Child of ScrollViewer -->

<!-- TextBlocks for the column are placed here -->

</StackPanel>

</ScrollViewer>

<ScrollViewer Grid.Column="2">

<StackPanel Orientation="Vertical"> <!-- Child of ScrollViewer -->

<!-- TextBlocks for the column are placed here -->

</StackPanel>

</ScrollViewer>

</Grid>

</Grid>

</Page>

Figure 3-12 shows the page of the Windows Store app for the XAML. Whenever the mouse hovers over the app or the user touches the surface, scrollbars appear for each column. In this example, the user can scroll vertically to view the content of each column.

A screenshot of an app with three columns. Each column has more content than can be displayed on one page. Each column has a scroll bar to the right.

Figure 3-12. An app with multiple columns, each with a ScrollViewer in which the content is embedded

In addition to providing support for a dynamic layout in pages, the ScrollViewer control has built-in support for touch and zoom. By default, it enables the pinch-to-zoom touch gestures on the content. The properties of the ScrollViewer relevant for zooming are the following:

§ ZoomMode. This is a Boolean that indicates whether zooming is available in the ScrollViewer. The values allowed for this property are Enabled and Disabled.

§ ZoomFactor. This property sets the current value for scaling content. The default value of this property is 1.0, which indicates no scaling. Use the ZoomToFactor method to change the value of this property at runtime.

§ MinZoomFactor. and MaxZoomFactor These properties specify the minimum and maximum runtime values for ZoomFactor. The default value of MinZoomFactor is 0.1, and the default value of MaxZoomFactor is 10.0.

§ IsZoomChainingEnabled. This property specifies whether zoom chaining is enabled from this child to its parent. Zoom chaining controls whether the zooming action carried out by the user on a child element should be available on the parent ScrollViewer control.

§ IsZoomInertiaEnabled. This property specifies whether the zoom actions should include inertia in their behavior and value. Inertia in zooming action slows down the effect of zooming in or out of a UI element.

You can provide snap points in a Windows Store app to control zooming behavior. Snap points are logical points at which manipulation of content is stopped, and a subset of the content is visible in the page. It is recommended you provide snap points at common zoom resolutions, such as 100%, 75%, 50%, and 25%. You can provide mandatory snap points in your app for the user to continue panning the content until a snap point is reached, or you can provide proximity snap points to continue panning only when the current location is close to a snap point. You can specify a list of zoom snap points through the ZoomSnapPoints property and the zoom behavior through the ZoomSnapPointsType property. The value of the ZoomSnapPointsType property is set by using the SnapPointsType enumeration, as described in Table 3-3.

Table 3-3. SnapPointsType enumeration members

MEMBER

VALUE

DESCRIPTION

None

0

No value is set.

Optional

1

Viewer will snap to points when the current location is close to a snap point.

Mandatory

2

Viewer will always snap to a snap point on interaction.

OptionalSingle

3

Snap points are optional and cannot be jumped over.

MandatorySingle

4

Snap points are mandatory and cannot be jumped over.

Managing text flow and presentation

Windows Store apps that display textual content use either the TextBlock or the RichTextBlock controls. Both these controls have different use cases. The TextBlock control is used in the most basic cases where some text needs to be displayed. When your app needs to embed text with advanced formatting such as including UI elements, such as a hyperlink to a webpage or needs to display text in multiple columns for better readability, the RichTextBlock class can be used in such scenarios.

The TextBlock class can be used with a ScrollViewer control in the layout of a page. This ensures the text that overflows the visible screen area can be viewed by the user with the scrollbars or panning using touch. In its simplest form, you can use the TextBlock control within a ScrollViewercontrol, as shown in the XAML code in Using a TextBlock control in a ScrollViewer control.

USING A TEXTBLOCK CONTROL IN A SCROLLVIEWER CONTROL

<Page>

<Grid x:Name="PageLayoutRoot">

<Grid.RowDefitions>

<RowDefinition Height="140" />

<RowDefinition Height="*" />

</Grid.RowDefinitions>

<Grid Grid.Row="0">

<TextBlock Text="TextBlockSample"

Style="{StaticResource PageHeaderTextStyle}" />

</Grid>

<Grid Grid.Row="1">

<Grid.ColumnDefinitions>

<ColumnDefinition Width="*" />

</Grid.ColumnDefinitions>

<!-- The ScrollViewer is set up with a left margin of 120 pixels or 6 units -->

<ScrollViewer Margin="120,0,0,40" Grid.Column="0">

<TextBlock TextWrapping="Wrap" Margin="0,0,20,0">

<Run FontSize="28">

<!-- Text removed for brevity -->

Lorem ipsum dolor sit….

</Run>

<LineBreak />

<Run FontSize="28" FontStyle="Italic">

<!-- Text removed for brevity -->

Aenean orci ante,…

</Run>

</TextBlock>

</ScrollViewer>

</Grid>

</Grid>

</Page>

Figure 3-13 shows the Windows Store app with the text displayed.

A screenshot of a Windows Store app showing a text block populated with placeholder text that scrolls off the page. The left margin is much wider than the right margin. A scroll bar appears on the right side of the window.

Figure 3-13. A Windows Store app with a TextBlock placed within a ScrollViewer control

You can use the Text property of the TextBlock control to set the text; however, you can also place a block text within <Run> tags to format it. You can use multiple Runs in the same TextBlock to apply finer control on formatting the text. Note that a LineBreak element is not allowed within aRun element. Similar to the Run element, Windows provides the Underline element to embed text for underlining because there is no property on the TextBlock to achieve this. The following are properties of the TextBlock class:

§ CharacterSpacing. This property sets the spacing between characters in units of a thousandth of an em. Note that an em is equal to the font size of the element. You can use a negative value to reduce spacing between letters.

§ FlowDirection. This property sets the direction of text flow and other UI elements within the TextBlock. The property can be set to either LeftToRight (the default) or RightToLeft.

§ Font properties. The FontFamily, FontSize, FontStretch, FontStyle, and FontWeight properties customize the look and feel of the font used in the TextBlock.

§ IsTextSelectionEnabled. This property specifies whether text selection is enabled in the TextBlock. It can be either False (the default value) or True.

§ LineHeight. This property sets the height of each line in the TextBlock, specified in device-independent pixels. A value of zero (the default value) indicates the line height is determined automatically from the characteristics of the font used in the text block. A nonzero value sets the height specified in pixels.

§ LineStackingStrategy. This property specifies how a line box will be determined for each line. The default value is MaxHeight, which is the smallest value that contains all the inline elements on that line when those elements are properly aligned. It can be set to BlockLineHeight and used in conjunction with the LineHeight property to set the line height. Finally, it can be set to BaselineToBaseline, which sets the value to the distance between text baselines.

§ TextAlignment. This property specifies the horizontal alignment of the text content. It can have one of four values: Center, Left, Right, or Justify. The default value is Left.

§ TextTrimming. This property sets the behavior of the text in case it doesn’t fit within the available content area. You can set it to either None (the default value) so that text is clipped when it overflows, or WordEllipsis, which places an ellipsis in the end.

§ TextWrapping. This property specifies whether text can wrap into additional lines. You can set it NoWrap (the default value) or Wrap.

A Windows Store app such as a news or periodical reader can display figures inline and use multi-column layouts to arrange text in the available surface area. The RichTextBlock class provides more advanced formatting capabilities than the TextBlock control. The content in a RichTextBlock is set using the Paragraph element. In addition to applying bold, italic, or underline formatting to text in a Paragraph element with <Bold>, <Italic>, and <Underline> tags, respectively, you can embed one or more UI elements derived from the UIElement class; for example, images by using the InlineUIContainer class. The XAML of the TextBlock sample in Using a TextBlock control in a ScrollViewer control can be modified to use a RichTextBlock and include an InlineUIContainer to display an image inline. See the XAML code in Using a RichTextBlock and InlineUIContainer in a TextBlock control.

USING A RICHTEXTBLOCK AND INLINEUICONTAINER IN A TEXTBLOCK CONTROL

<Page>

<Grid x:Name="PageLayoutRoot">

<Grid.RowDefitions>

<RowDefinition Height="140" />

<RowDefinition Height="*" />

</Grid.RowDefinitions>

<Grid Grid.Row="0">

<!-- Content for title, etc -->

</Grid>

<Grid Grid.Row="1">

<Grid.ColumnDefinitions>

<ColumnDefinition Width="*" />

</Grid.ColumnDefinitions>

<ScrollViewer Margin="120,0,0,40" Grid.Column="0">

<RichTextBlock TextWrapping="Wrap" Margin="0,0,20,0">

<Paragraph FontSize="28">

<!-- Text removed for brevity -->

Lorem ipsum dolor sit….

</Paragraph>

<Paragraph FontSize="28" FontStyle="Italic">

<InlineUIContainer>

<Image Source="Assets/MediumGray.png" Stretch="None" />

</InlineUIContainer>

<Bold>Aenean orci ante</Bold>,…

<!-- Text removed for brevity -->

</Paragraph>

</RichTextBlock>

</ScrollViewer>

</Grid>

</Grid>

</Page>

Figure 3-14 shows the Windows Store app with the text displayed using a RichTextBlock and InlineUIContainer to display an image.

A screenshot of a Windows Store app showing two paragraphs with a gray rectangle between the paragraphs. The first three words in the second paragraph are displayed in bold and italics; the rest of the second paragraph is in italics only.

Figure 3-14. A Windows Store app with a RichTextBlock control with InlineUIContainer for an image; they are placed within a ScrollViewer control

In the examples so far, we have used a ScrollViewer to make the text readable in a TextBlock or a RichTextBlock control when it does not fit in the available surface area. You can use an element called RichTextBlockOverflow to display text that spills over from a RichTextBlock. If the content doesn’t fit in one RichTextBlockOverflow, it can spill into another RichTextBlockOverflow, and so on.

To use RichTextBlockOverflow, set the RichTextBlock OverflowContentTarget property to an instance of RichTextBlockOverflow. RichTextBlockOverflow has its own OverflowContentTarget property; therefore, you can keep adding OverflowContentTarget in a sequence. In Chaining RichTextBlockOverflow elements with a RichTextBlock, two RichTextBlockOverflow elements are chained with a single RichTextBlock, and the text font size varies with the slider.

CHAINING RICHTEXTBLOCKOVERFLOW ELEMENTS WITH A RICHTEXTBLOCK

<StackPanel Margin="20,0,0,50">

<TextBlock TextWrapping="Wrap" Text="FontSize:" Margin="0, 0, 20, 0"/>

<Slider x:Name="fontSizeSlider" Width="200" Value="16" Minimum="8" Maximum="24"

TickFrequency="4" Orientation="Horizontal" HorizontalAlignment="Left" />

</StackPanel>

<Grid x:Name="columnGrid" Width="900" Height="300">

<Grid.ColumnDefinitions>

<ColumnDefinition/>

<ColumnDefinition/>

<ColumnDefinition/>

</Grid.ColumnDefinitions>

<RichTextBlock Grid.Column="0"

FontSize="{Binding Value, ElementName=fontSizeSlider}"

OverflowContentTarget="{Binding ElementName=firstOverflowContainer}"

TextAlignment="Justify" Margin="20,0" FontFamily="Segoe UI">

<Paragraph>

<!-- Text Content -->

</Paragraph>

</RichTextBlock>

<RichTextBlockOverflow x:Name="firstOverflowContainer" Grid.Column="1"

OverflowContentTarget="{Binding ElementName=secondOverflowContainer}"

Margin="20,0"/>

<RichTextBlockOverflow x:Name="secondOverflowContainer" Grid.Column="2"

Margin="20,0"/>

</Grid>

Figure 3-15 shows how RichTextBlockOverflow arranges the text in two columns with the default font size.

A screenshot of a Windows Store app showing a slider for adjusting relative font size, and two columns of text in a small font size. The text displayed in the app is not legible enough to be read comfortably.

Figure 3-15. Screenshot of a Windows Store app showing a RichTextBlock control with two RichTextBlockOverflow controls for displaying text that does not fit in the RichTextBlock

At the default font size, the text shown in Figure 3-15 is almost impossible to read. When the user selects a larger font size with the slider, the text spills over to the second RichTextBlockOverflow control and is displayed legibly, as shown in Figure 3-16.

A screenshot of the Windows Store app shown in  with the font size increased. The text now spans three columns and is more legible.

Figure 3-16. The Windows Store app shown in Figure 3-15 with an increased font size; the text uses the additional RichTextBlockOverflow control to render the text

To make it easier to display text using the RichTextBlock and RichTextBlockOverflow controls, Visual Studio provides a control called RichTextColumns with the Grid App and Split App Windows Store application templates. This control is located in the Common folder in your application’s project directory. To use the control, set the Width and Margin properties of the RichTextBlockOverflow control. Depending on the style of the text, the RichTextColumns control creates one or more RichTextBlockOverflow controls to display the text.

THOUGHT EXPERIMENT

Understanding advantages of Windows Store apps over desktop applications

In this thought experiment, apply what you’ve learned about this objective. You can find answers to these questions in the “Answers” section at the end of this chapter.

Your organization has been invited to present a proposal to build a Windows Store app for a designer and manufacturer of engineering equipment. The manufacturer currently uses a desktop app with no touch support to create, view, and edit 3D models of heavy engineering machinery and visualize graphs of various manufacturing processes.

Your responsibility is to select three important advantages of Windows Store apps over traditional desktop applications and present them to the customer. Select the three features you will present from what you have learned in this chapter.

Objective summary

§ You should design a Windows Store app to adapt to changes in screen size, resolution, and orientation.

§ Use the Grid control to create flexible layouts in Windows Store apps. A Grid control has rows and columns with adjustable dimensions for creating fixed and fluid layouts.

§ The ScrollViewer control can be used to lay out content that overflows a visible area in the screen. The control has built-in support for touch and zoom.

§ The TextBlock control can be used with the ScrollViewer control to display text in a Windows Store app. Text is wrapped within the TextBlock, and the ScrollViewer provides the virtual surface area to render the text.

§ Use the RichTextBlock control to display text embedded with photos or hyperlinks, for example. You can use the companion control, RichTextBlockOverflow, to display text that does not fit in the RichTextBlock control.

Objective review

Answer the following questions to test your knowledge of the information in this objective. You can find the answers to these questions and explanations of why each answer choice is correct or incorrect in the “Answers” section at the end of this chapter.

1. You have developed a Windows Store app with a grid layout using fixed row heights and column widths. Your testers have reported that controls overlap each other in the portrait orientation. However, the UI appears properly in other orientations. What is the best solution for this problem?

a. Create and apply styles and control templates for the portrait orientation.

b. Use proportional ratios and star sizing for the dimensions of rows and columns. Wherever necessary, adjust the size of controls using styles and templates for various view states.

c. Remove the Grid control and create your own layout for the portrait orientation.

d. Place the controls in a ScrollViewer and let the user scroll or pan through the content.

2. While testing your news reader application, you find that in some news articles, pictures cause the text to overflow and often get clipped. The main UI element is a RichTextBlock control within a ScrollViewer to allow content to be scrolled vertically. You want to enhance the user experience in all view states. Which implementation choices should you make? (Choose all that apply.)

a. Develop a custom control and use it as the root UI element to lay out controls in the page.

b. Use a RichTextBlock embedded in the root UI element.

c. For the various view states, use star sizing to lay out RichTextBlock controls in columns. Consider using grid layouts for specific view states with styles and templates.

d. Use RichTextBlockOverflow controls with the parent RichTextBlock control display overflow content.

e. Use the VisualStateManager class to switch between styles and templates for various view states.

3. How do you justify using the Grid control along with the ScrollViewer control to lay out content in your Windows Store app? (Choose all that apply.)

a. The Grid control can be used with star sizing to create a fluid layout that adapts easily to changes in screen size, resolution and orientation.

b. The Grid control is the only control available for layout of content in Windows Store apps.

c. The ScrollViewer control is capable of supporting only horizontal scrolling, so it is suitable for building apps that have content placed in the horizontal direction.

d. The ScrollViewer control has built-in touch and zoom capabilities, handy for devices that support multi-touch.

e. The ScrollViewer control presents a virtual surface area where content can overflow but be visible though scrolling or panning.

Objective 3.3: Design and implement the app bar

App bars in Windows Store apps provide users with a consistent way to access commands whenever they need them in the context of the current page (and even for the app) to navigate through various sections in an app. App bars (a bottom app bar and, optionally, a top app bar) are hidden by default and are accessible with a swipe gesture from the bottom of the screen, with a right-click of the mouse, or with the Windows+Z keyboard shortcut. They are dismissed when the user makes an edge swipe or when the user interacts with the user. App bars can also be shown and hidden programmatically.

Windows Store app developers should consider using the app bars to place commands in the context of the page as well as navigation shortcuts. Commands that are relevant to a page might not be required in other pages of your app. To provide consistent user experience, you should ensure that commands likely to be used most often are placed at the two edges of the app bar because these edges can be reached easily by the user’s fingers. The fundamental rule for creating commands that are placed in the bottom app bar is that they should directly interact with the content presented in the page. The top app bar should be used for global commands and navigation within the app. This design helps the user to focus on the content in your app and prevents distraction from commands that are not frequently used.

NOTE

This objective covers how to:

§ Determine what to put on the app bar based on app requirements.

§ Design the placement of controls in the app bar.

§ Style and position app bar items.

§ Handle AppBar events.

Determining what to put on the app bar based on app requirements

Designing the UI of your Windows Store with a consideration for the commands you will require to implement in every page is quite important. In your design, if you display the content in a page without including any distractions, such as buttons or drop-downs, the user will most likely find it easy to use your app. However, a dynamic, interactive app needs commands available for common operations throughout the app.

You have the option to use the charms bar for implementing common app commands such as search, share, and configuring settings. However, having page-specific commands in the charms bar is not a good UI design and actually violates Microsoft design principles. Therefore, you should consider the app bars as placeholders for commands that help the user interact with your app.

We can draw some conclusions about the design pattern followed in app bars by examining the Weather app shown in Figure 3-17:

A screenshot of the Weather app showing content and two app bars. The top app bar contains the Home, Places, and World Weather commands. The bottom app bar contains a command on the left, Change Home, which is specific to the page. The Current Location, Change to Fahrenheit, and Refresh commands, which are available in other pages of the app, are located on the right side of the bottom app bar.

Figure 3-17. The Weather app showing content and the two app bars

§ Commands are placed in the app bar starting from the right edge.

§ The top app bar is used for navigation between various sections of an app.

§ The bottom app bar contains commands that invoke actions specific to the page.

§ Commands that are available in multiple pages of an app are placed separate from commands specific to a page.

The app bar in a Windows Store app can contain commands that are used to help the user find the right content to explore or share, such as by providing filters that can be selected one at a time. The Bing app, which you saw in Chapter 2, provides this functionality. The app bar can contain commands that help the user select a specific view of the page while remaining in the page; for example, the day, week, and month views in a calendar app. Common guidelines for app bars are summarized as follows:

§ Use command groups to group distinct sets of commands and place them at opposite sides of the app bar. For example, if you have two set of commands in a page, one for creating new content and the other for operating on existing content such as applying filters, place them on opposite sides of the app bar. If you have more than two sets of commands in a page, use a separator to separate them.

§ If you need to implement app bars in multiple pages, make sure the commands in the app bars are in the same location or as close to the same location as possible.

§ Separate critical commands from other commands to avoid accidental execution.

§ Show the app bars automatically whenever an item in the content is selected. Because most users are right-handed, contextual commands for the item should be placed in the left side of the app bar. This will prevent their arms or hands from blocking their view of the commands.

§ When there are too many commands to fit in the app bar, consider using context menus and flyouts.

§ Microsoft provides default styles for commands, menus, and flyouts. Use these default styles in your application to arrange commands in the app bar. The default layout is designed to support touch and to fit up to 10 commands on all supported screen widths. You can change the color of the background, icons, and labels, but avoid changing the size or padding of the buttons.

§ Design your app bar for snap and portrait views. The horizontal dimensions of the app in these views are different, and special attention is required to lay out the commands in the app bar in these views. If you have up to 10 commands, Windows automatically hides labels and adjusts padding in the app bar when the user snaps your app or rotates to the portrait orientation.

§ You should provide tooltips for the commands in the app bar. This is helpful in view states when the system hides the labels in the buttons.

§ Use the top app bar for navigation and the bottom app bar for commands.

§ Whenever there are contextual commands in the app bar, make the app bar sticky so it is not dismissed when the user touches in the main area of the screen. For example, in a photo-editing program, the app bar should be visible as long as the user is editing the photo displayed on the screen.

§ If your app requires horizontal scrolling, reduce the height of the scrollable area when the app bar appears in sticky mode to avoid content from being hidden beneath the app bar. You can set the Background property of the app bar to {x:Null} to prevent the app bar from blocking taps and clicks on content beneath the app bar.

§ Whenever possible, use the built-in icons for commands to have a consistent appearance with other apps.

§ Avoid putting critical commands in your app bar. For example, in a camera application, the button to take a photo should be placed in the main surface, not in the app bar.

§ Do not put Clipboard commands such as cut, copy, and paste in the app bar; put them in a context menu in the app page instead.

§ Do not put settings commands, search, and commands for sharing content in the app bar. Use the charms available for these operations.

§ The background of the app bar can match your app’s main color.

You should also consider cases when the user is likely to use the right mouse button to interact with your app. In most applications, right-clicking the app displays the app bar. However, if your app depends on critical commands to be carried out with right-click, it should ignore the events that show the app bar. To provide a consistent user experience, consider using the app bar for other commands. Here are some guidelines for implementing the UI with the right mouse button in mind:

§ If your app depends on a right mouse click for a critical function, use it for that function only. Ignore the events that are raised for the app bar and do not activate any contextual UI.

§ Open the app bar when right-clicking regions of the app that do not require app-specific actions, such as the borders.

§ If your app needs right mouse click support in the whole canvas, consider showing the app bar when the user right-clicks the topmost horizontal row of pixels, the bottommost horizontal row of pixels, or both.

§ Do not provide an alternative behavior for the Windows+Z keyboard combination in your app.

The top app bar can be used in conjunction with the traditional navigation mechanism of using the Back button in a Windows Store app. The top app bar is convenient for switching between various contexts within an app; for example, multiple tabs in a browser, various categories of news items in a news reader, and so on. You should consider using a simple thumbnail for each item in the top app bar.

Designing the placement of controls on the app bar

When you choose to use the app bar to include commands for the page currently in view, button placement in the app bar is important. You should group the commands that act on existing content in the page in view on the right edge of the app bar, grouping similar commands in a section with a separator between them, and commands that create new content or are not specific to the page on the left edge of the app bar. This placement provides ease of use to right-handed users because they are likely to use the buttons on the right edge of the app bar.

In a Windows Store app, such as for an MP3 player, you declare the bottom app bar and arrange the buttons for the various commands such as play, pause, and stop as shown in Declaring a bottom app bar and arranging command buttons.

DECLARING A BOTTOM APP BAR AND ARRANGING COMMAND BUTTONS

<Page.BottomAppBar>

<AppBar x:Name="bottomAppBar" IsSticky="True">

<Grid>

<Grid.RowDefinitions>

<RowDefinition Height="Auto"/>

</Grid.RowDefinitions>

<StackPanel x:Name="leftAppBarPanel" Orientation="Horizontal">

<Button Style="{StaticResource FolderppBarButtonStyle}"/>

<Button Style="{StaticResource OpenFileAppBarButtonStyle}"/>

</StackPanel>

<StackPanel x:Name="rightAppBarPanel"

Orientation="Horizontal" HorizontalAlignment="Right">

<Button Style="{StaticResource SkipBackAppBarButtonStyle}"/>

<Button Style="{StaticResource SkipAheadAppBarButtonStyle}"/>

<Line X1="0" Y1="60" Margin="0,10,0,0"

StrokeThickness="1" Stroke="White"></Line>

<Button Style="{StaticResource PlayAppBarButtonStyle}"/>

<Button Style="{StaticResource PauseAppBarButtonStyle}"/>

<Button Style="{StaticResource StopAppBarButtonStyle}"/>

</StackPanel>

</Grid>

</AppBar>

</Page.BottomAppBar>

In Declaring a bottom app bar and arranging command buttons, notice how a vertical line separates groups of app bar controls for specific features. Figure 3-18 shows the app bar with the separator.

A screenshot of the app bar for a Windows Store MP3 player app. Commands that are used more often and act on the content in display are placed on the right side of the app bar, and commands that are used globally are placed on the left. A relatively large blank area separates controls on the left from controls on the right.

Figure 3-18. An app bar for a Windows Store MP3 player app

A Windows Store MP3 player app is likely to be used along with other applications by the user, with the MP3 player snapped to one side of the screen, as shown in Figure 3-19.

A screenshot of the app bar for a Windows Store MP3 player app in the snapped view state. The snapped app displays only the Play, Pause, and Stop buttons, which are relatively close together.

Figure 3-19. App bar of a MP3 player Windows Store app in the snapped view state

In the snapped and full screen portrait view states, you can use the Styles and VisualStates of the app bar buttons to hide each button’s label and reduce its width. The various VisualStates of app bar buttons are defined in StandardStyles.xaml (which you learn about shortly); however, controls are not aware of changes in their view state. If your application uses one of the standard Windows Store app templates provided by Visual Studio, you can use the StartLayoutUpdate method provided by the LayoutAwarePage base class to register and receive visual state changes that correspond to app view state changes. Therefore, an app bar button can go to the snapped view state when your application is snapped. The app bar of the MP3 player application you have seen previously is shown in Figure 3-20, in the snapped state.

A screenshot of the app bar for a Windows Store MP3 player app in the snapped view state with VisualStates used for the buttons. The buttons, from left to right, are Folder, Open File, Play, Pause, and Stop. The Folder and Open File buttons are separated from the other buttons by a separator bar. All buttons are relatively close together. The buttons do not have labels.

Figure 3-20. App bar of a Windows Store MP3 player app in the snapped view state with VisualStates used for the buttons

Figure 3-21 shows the app bar after the app’s orientation changes to portrait, and the buttons are resized.

A screenshot of the app bar for a Windows Store MP3 player app in the full screen portrait view state with VisualStates used for the buttons. The buttons on the left are Folder and Open File. They are followed by a large, blank space. On the right side of the app bar are the Rewind and Fast Forward buttons followed by a separator bar, and then the Play, Pause, and Stop buttons. None of the buttons has a label.

Figure 3-21. App bar of a Windows Store MP3 player app in the full screen portrait view state with VisualStates used for the buttons

Styling and positioning app bar items

Visual Studio provides the StandardStyles.xaml file, which contains styles and resources that enable you to match the design of other Windows Store apps. The file includes 192 styles for app bar buttons. These styles are based on the AppBarButtonStyle resource, which provides the templates and visual states for the app bar buttons. AppBarButtonStyle uses a glyph from the Segoe UI Symbol font as the icon visible in the button. By default, the app bar button styles are commented out in the StandardStyles.xaml file, and you should uncomment the styles you use in your app.Providing the style for an app bar button shows the XAML for EditAppBarButtonStyle.

PROVIDING THE STYLE FOR AN APP BAR BUTTON

<Style x:Key="EditAppBarButtonStyle" TargetType="Button"

BasedOn="{StaticResource AppBarButtonStyle}">

<Setter Property="AutomationProperties.AutomationId" Value="EditAppBarButton"/>

<Setter Property="AutomationProperties.Name" Value="Edit"/>

<Setter Property="Content" Value=""/>

</Style>

The style of an app bar button is designed to look for the value of AutomationProperties.Name, typically used in UI automation scenarios. It uses the value of the String property as the text for a TextBlock below each circle. It is a good practice to specify the value ofAutomationProperties.AutomationId because it is useful in creating test scripts for testing the UI. You can use this principle to create your own app bar button style; for example, Creating a button style for an Edit app bar button shows the XAML for an Edit app bar button with an icon.

CREATING A BUTTON STYLE FOR AN EDIT APP BAR BUTTON

<Button Style="{StaticResource EditAppBarButtonStyle}"

AutomationProperties.Name ="Edit"

AutomationProperties.AutomationId="EditAppBarButton">

<Image Source="Assets/Icons/AppBar/Edit.png"/>

</Button>

Although the XAML in Creating a button style for an Edit app bar button provides you the flexibility to use your own icons, it can be tedious to provide assets for every icon and create styles for them. Whenever possible, use the styles provided by Visual Studio. If you need to look up a certain symbol to use in an app bar button style, use the Character Map tool, shown in Figure 3-22.

A screenshot of the Character Map tool showing the various icons in the Segoe UI Symbol font family. You can copy the characters from this tool and use them as icons in the buttons in the app bar. In the screenshot, the groups icon is selected, which displays the hexadecimal value, at the bottom of the dialog box. You can copy the value into the XAML style.

Figure 3-22. Character Map tool showing the various icons in the Segoe UI Symbol font family; the groups symbol is selected

You can copy and paste characters directly into your app or use the XML escape sequence &#xHexValue, where HexValue is the hexadecimal value shown in the bottom of the Character Map tool after you select a symbol. The following XAML is for an app bar button for the groups symbol:

<Style x:Key="GroupsAppBarButtonStyle" TargetType="Button"

BasedOn="{StaticResource AppBarButtonStyle}">

<Setter Property="AutomationProperties.AutomationId" Value="GroupsAppBarButton"/>

<Setter Property="AutomationProperties.Name" Value="Groups"/>

<Setter Property="Content" Value=""/>

</Style>

The button created with the XAML is shown in Figure 3-23.

A screenshot of the Groups app bar button with a custom style.

Figure 3-23. App bar button with a custom style defined in XAML

In the previous example, you saw how to use the Character Map tool and a style definition to create an app bar button. You can also choose a font family in the Character Map tool, select a character, copy its hex value, and use it with the Content property of a button. You can also use your own images from the assets available in the app as icons for buttons in the app bar. If you require an icon that is not available as a font glyph or as an image, you can use a XAML Path element to specify an icon. When you create an icon using Path, it does not respond to state changes such as pointer over, pressed, and disabled (unlike a font glyph). This is because a Path element does not have a Foreground property, so you must change its Stroke and Fill properties instead.

Handling AppBar events

You can set up the app bar in your Windows Store app using XAML with button styles. Each button you include has a Click event for which you provide an event handler. The app bar raises a number of events; some common events are described as follows:

§ Loaded. Raised when the app bar has been constructed and is available to the user.

§ Unloaded. Raised when the app bar is no longer available as a visual element.

§ Opened. Raised when the app bar is visible.

§ Closed. Raised when the app bar is no longer visible.

§ Tapped. Raised when the user taps on the app bar. When the user clicks on a button in the app bar, the button’s Clicked event is raised.

You can use the Loaded and Unloaded events that are fired when the page is created or destroyed with the VisualStateManager class to change the styles of the app bar buttons when the view state changes, as shown in the XAML code in Changing app bar button styles when the view state changes.

CHANGING APP BAR BUTTON STYLES WHEN THE VIEW STATE CHANGES

<Page.BottomAppBar>

<AppBar x:Name="bottomAppBar" IsSticky="True"

Loaded="AppBar_Loaded" Unloaded="AppBar_Unloaded">

<Grid>

<Grid.RowDefinitions>

<RowDefinition Height="Auto"/>

</Grid.RowDefinitions>

<StackPanel x:Name="leftAppBarPanel" Orientation="Horizontal">

<Button Style="{StaticResource FolderppBarButtonStyle}"/>

<Button Style="{StaticResource OpenFileAppBarButtonStyle}"/>

</StackPanel>

<StackPanel x:Name="rightAppBarPanel"

Orientation="Horizontal" HorizontalAlignment="Right">

<Button Style="{StaticResource SkipBackAppBarButtonStyle}"/>

<Button Style="{StaticResource SkipAheadAppBarButtonStyle}"/>

<Line X1="0" Y1="60" Margin="0,10,0,0"

StrokeThickness="1" Stroke="White"></Line>

<Button Style="{StaticResource PlayAppBarButtonStyle}"/>

<Button Style="{StaticResource PauseAppBarButtonStyle}"/>

<Button Style="{StaticResource StopAppBarButtonStyle}"/>

</StackPanel>

</Grid>

</AppBar>

</Page.BottomAppBar>

The event handler code assumes that the app bar uses a layout with a Grid control as the root UI element that contains additional panels that host the buttons. Each Button is registered to receive state changes when the app bar is loaded and is unregistered when the app bar is unloaded. See the C# code in Receiving state changes when the app bar is loaded and unloaded.

RECEIVING STATE CHANGES WHEN THE APP BAR IS LOADED AND UNLOADED

private void AppBar_Loaded(object sender, RoutedEventArgs e)

{

// Get the App bar's root Grid.

Grid root = ((AppBar)sender).Content as Grid;

if (root != null)

{

// Get the Panels that hold the controls.

foreach (Panel panel in root.Children)

{

// Get each control and register for layout updates.

foreach (UIElement child in panel.Children)

{

base.StartLayoutUpdates(child, new RoutedEventArgs());

}

}

}

}

private void AppBar_Unloaded(object sender, RoutedEventArgs e)

{

// Get the app bar's root Grid.

Grid root = ((AppBar)sender).Content as Grid;

if (root != null)

{

// Get the Panels that hold the controls.

foreach (Panel panel in root.Children)

{

// Get each control and unregister layout updates.

foreach (UIElement child in panel.Children)

{

base.StopLayoutUpdates(child, new RoutedEventArgs());

}

}

}

}

You can update the UI using the Opened and Closed event, for example, to change the margin of a layout so buttons critical for user interaction are not hidden underneath the app bar. Setting the IsSticky property to True will make the app bar visible when the user interacts with the page. Close the app bar by setting its IsOpen property to False.

THOUGHT EXPERIMENT

Building a Windows Store app with app bar

In this thought experiment, apply what you’ve learned about this objective. You can find answers to these questions in the “Answers” section at the end of this chapter.

You are building a Windows Store app that will be used in handheld devices and desktop PCs. In your design, you have considered using the app bar to provide commands to users.

Answer the following questions regarding app design:

1. Will you use the app bar to implement search and share in your app? Why or why not?

2. You have decided to use the top app bar to provide navigation shortcuts. What is the advantage of this decision?

3. How will you support changes in the layout of the app bar in multiple view states in your app?

Objective summary

§ The app bars in a Windows Store app provide a simple and intuitive surface for placing navigation and in-context commands. Use the app bar to add commands in your app for the design to be consistent with other apps.

§ Follow the design guidelines for app bars while designing them.

§ Actions such as search, share, and settings should be performed using the charms bar; these commands should not be implemented in the app.

§ Group similar commands on the app bar. Separate commands that are critical to the app’s execution from other commands to prevent the critical commands from being accidentally invoked.

§ You should use the app bar button styles defined in the StandardStyles.xaml file whenever possible. You can use standard font families, your own images, or XAML paths to customize the appearance of the app bar buttons.

§ Consider various view states your app can be in while designing the app bars. The Opened and Closed events can be used to set up the app bar in different view states.

Objective review

Answer the following questions to test your knowledge of the information in this objective. You can find the answers to these questions and explanations of why each answer choice is correct or incorrect in the “Answers” section at the end of this chapter.

1. You are developing a Windows Store text editor app. You have implemented a number of commands using buttons; however, during a usability review, you have been asked to remove some of the commands from the surface and move them into the app bar. Which functionality should you move to the app bar? (Choose all that apply.)

a. Searching within text

b. Cutting, copying, and pasting

c. Increasing and decreasing the font size

d. Creating, editing, and deleting a new file

e. Sending a file as an email attachment

2. What can you use as icons in app bar buttons, in addition to the styles provided in application templates? (Choose all that apply.)

a. Hexadecimal code for a font symbol from a font family

b. An image asset available within your app

c. None; the system automatically sets the images for the buttons, so there is no need to provide images

d. A XAML Path

e. An image located somewhere on the Internet

3. You are building a Windows Store app with commands in the app bar. The app supports all view states for a better user experience. Which events and/or properties of the AppBar class should you use? (Choose all that apply.)

a. Loaded event to subscribe to layout update events

b. Unloaded event to unsubscribe from layout update events

c. IsSticky set to True to make the app bar persistent in pages where the interaction requires commands from the app bar

d. Opened event to create the app programmatically

e. Closed event to destroy the app bar programmatically

Objective 3.4: Design and implement data presentation

Windows Store apps that follow the Microsoft design style and use the basic set of controls provide a consistent user experience. Similarities among apps are seen in the layout of controls, presentation of content, and patterns of interaction through gestures and commands. This helps users to rapidly adopt the user experience of these applications. Whenever there is a list of data that needs to be displayed along with navigation to the details of each item, data controls play an important role.

Windows provides developers with a number of data controls for use in applications in which data plays a central role. The GridView and ListView controls are typically used in scenarios in which an individual item in the list has some details and needs to be viewed in a separate page. TheFlipView control is useful in scenarios in which photos in an album or pages of text need to be displayed in sequence.

NOTE

This objective covers how to:

§ Choose and implement data controls to meet app requirements.

§ Create data templates to meet app requirements.

Choosing and implementing data controls to meet app requirements

The ListView and GridView controls are useful in applications that display data in a list or grid, respectively. Typically, users tap an item in a list and view the details of the item, pan or scroll through the items, and use zooming to view the data as categories or groups. Both these controls are derived from the ListViewBase base class, which provides all the methods, properties, and events available in these controls. Thus, a GridView is a grid of items, and a ListView is a list of items. The FlipView control displays a list of items as a sequence with a “flip” behavior to traverse through the collection of items.

The GridView control

The GridView control enables you to display a list of data that can be scrolled or panned horizontally. It can also handle grouped data. This means you can arrange categories of data in groups and add subheaders to mark categories present in the data. It provides you with a control template that can be used to customize the way individual items are arranged and a data template for individual items.

You can customize the GridView control to make individual items of variable height and width. In your Windows Store app, you might want to highlight a particular data item by making the size of an item larger than the others in the same category. In applications in which a large dataset is displayed using a GridView, navigation among categories can pose a serious challenge to the user. The GridView supports Semantic Zoom, which provides an easy way to navigate categories or groups of data in the GridView. Semantic Zoom alters the visual appearance of content when the user zooms in or out of the content displayed in the GridView. For example, the zoomed-out view can be represented by thumbnails of categories or groups of data, and the zoomed-in view can contain a fixed number of data items.

The GridView control provides a layout to display data so that the user can drill down to the details of an item, browse through large sections of data, and respond to changes in the view state. The Windows Store Grid App template provided by Visual Studio helps you build apps with theGridView control. In its default form, the main application page with a GridView control is shown in Figure 3-24.

A screenshot of the Grid App template Sample page with multiple groups of item placeholders. The groups scroll off of the page to the right.

Figure 3-24. The GridView control used in the Windows Store Grid App template provided by Visual Studio

The XAML used for laying out the GridView in the page is shown in Laying out the GridView.

LAYING OUT THE GRIDVIEW

<GridView

x:Name="itemGridView"

AutomationProperties.AutomationId="ItemGridView"

AutomationProperties.Name="Grouped Items"

Grid.RowSpan="2"

Padding="116,137,40,46"

ItemsSource="{Binding Source={StaticResource groupedItemsViewSource}}"

ItemTemplate="{StaticResource Standard250×250ItemTemplate}"

SelectionMode="None"

IsSwipeEnabled="false"

IsItemClickEnabled="True"

ItemClick="ItemView_ItemClick">

<GridView.ItemsPanel>

<ItemsPanelTemplate>

<VirtualizingStackPanel Orientation="Horizontal"/>

</ItemsPanelTemplate>

</GridView.ItemsPanel>

<GridView.GroupStyle>

<GroupStyle>

<GroupStyle.HeaderTemplate>

<DataTemplate>

<Grid Margin="1,0,0,6">

<Button

AutomationProperties.Name="Group Title"

Click="Header_Click"

Style="{StaticResource TextPrimaryButtonStyle}" >

<StackPanel Orientation="Horizontal">

<TextBlock Text="{Binding Title}" Margin="3,-7,10,10"

Style="{StaticResource GroupHeaderTextStyle}" />

<TextBlock Text="{StaticResource ChevronGlyph}"

FontFamily="Segoe UI Symbol"

Margin="0,-7,0,10"

Style="{StaticResource GroupHeaderTextStyle}"/>

</StackPanel>

</Button>

</Grid>

</DataTemplate>

</GroupStyle.HeaderTemplate>

<GroupStyle.Panel>

<ItemsPanelTemplate>

<VariableSizedWrapGrid Orientation="Vertical" Margin="0,0,80,0"/>

</ItemsPanelTemplate>

</GroupStyle.Panel>

</GroupStyle>

</GridView.GroupStyle>

</GridView>

In the declaration of the GridView control, a number of properties define the style and data binding. The properties of the GridView control you will use most often are these:

§ ItemContainerStyle. This property specifies the style that is used when rendering the item containers. Item containers are used for laying out individual items in the GridView control.

§ ItemsSource. This property is the source of data for the GridView, typically a CollectionViewSource that consists of data organized in groups. This property is defined in the Page.Resources section in the XAML of a page.

§ ItemTemplate. This property sets the DataTemplate used to display each item in the GridView. A number of data templates are defined in the StandardStyles.xaml file added by Visual Studio when you create apps with a Windows Store project template. When used with a grouped data source, multiple child UI elements that make up the DataTemplate are used to visually represent the data.

§ ItemsPanel. This property sets the ItemsPanelTemplate that defines the panel used to lay out items in the GridView. If the value of this property is not set, a StackPanel is used as the default ItemsPanelTemplate. In Laying out the GridView, a VirtualizingStackPanel optimizes the display of items in a grid by creating only those UI elements that are currently visible on the screen.

§ SelectionMode. This property specifies the selection mode of items in the GridView. It can have one of these values: None, Single, Multiple, or Extended. In the Extended selection mode, the user can select multiple items from the GridView by entering into a special mode. When the Control key is pressed, the user can select multiple items using the space bar, a mouse click, or a touch tap on the screen. When the Shift key is pressed, the user can select multiple contiguous items by clicking or tapping on the first item and then the last item in the selection.

§ IsSwipeEnabled. This property indicates whether the GridView control will allow selection of items with the swipe gesture.

§ IsItemClickEnabled. This property indicates whether the items in the GridView can raise an ItemClick event when an item is clicked. The default value is set to False. When set to True, a click event is raised instead of triggering an item selection.

§ GroupStyle. This property specifies the style of each group of data in the GridView. The GroupStyle property is discussed in more detail later in this section.

§ CanDragItems, CanReorderItems and AllowDrop. These properties, when set to True, enable users to reorder items in a GridView. These properties can be individually set to True to allow a specific action to occur. For example, if CanDragItems is set to True and the rest are set to False, the user can drag items in a GridView; however, the items cannot be reordered or dropped elsewhere.

The GroupStyle property defines the style of each group of data. It has three important properties:

§ ContainerStyle. This property sets the style of the GroupItem generated for each item. A GroupItem is used to display of collection of items in a group in a GridView.

§ HeaderTemplate. This property sets the template used to display the header of each group of data.

§ Panel. This property specifies the ItemsPanelTemplate used to lay out individual ItemTemplate instances. An ItemsPanelTemplate contains a UI element derived from the Panel class; for example, the StackPanel or VirtualizingStackPanel class.

§ HidesIfEmpty. This property specifies whether items in empty groups should be displayed or not.

The CollectionViewSource is declared in the XAML as a resource in the Page.Resources section in the page. For grouped data, the data source consists of an IList or an IEnumerable collection of groups of items. For such a CollectionViewSource object, the IsSourceGrouped property is set toTrue, and the ItemsPath property is set to the collection of items present in the data source specified through the Source property. The following XAML code shows the configuration of a CollectionViewSource for the GridView described earlier:

<!-- This is declared within the Page.Resources section. The source of data for the

CollectionViewSource is set in the code-behind -->

<CollectionViewSource x:Name="groupedItemsViewSource"

Source="{Binding Groups}"

IsSourceGrouped="true"

ItemsPath="TopItems" />

The ItemClick event can be used with an event handler to show the details of an item in the GridView. This event is raised only when the IsItemClickEnabled property is set to True.

The ListView control

The ListView control is often used to display a list of data that can be scrolled or panned vertically. This control shares the same base class as the GridView control: ListViewBase. Other than their own constructors, the GridView and ListView controls do not extend the features of theListViewBase class. Items in a ListView control are arranged similar to the GridView control except that the default direction of scrolling or panning is vertical.

A good example of the ListView control used in app layouts is seen in the full screen portrait and snapped view states of a Window Store app. Visual Studio’s Grid App template uses a GridView control for fill and full screen landscape view states, and a ListView control for the other view states. Figure 3-25 shows an app in snapped and full screen portrait view states.

Screenshots of the ListView control used in the Grid App template. The sample page on the left is in snapped view; the sample page on the right is in full screen portrait view. The ListView control lays out items in the vertical direction that are viewed by scrolling or panning using swipe gestures.

Figure 3-25. ListView control used in the Grid App Windows Store app template provided by Visual Studio when the app is in the snapped and full screen portrait view states

The XAML used to configure a ListView control in the Grid App template in Visual Studio is shown in Configuring a ListView control.

CONFIGURING A LISTVIEW CONTROL

<ListView x:Name="itemListView"

AutomationProperties.AutomationId="ItemListView"

AutomationProperties.Name="Grouped Items"

Grid.Row="1"

Visibility="Collapsed"

Margin="0,-10,0,0"

Padding="10,0,0,60"

ItemsSource="{Binding Source={StaticResource groupedItemsViewSource}}"

ItemTemplate="{StaticResource Standard80ItemTemplate}"

SelectionMode="None"

IsSwipeEnabled="false"

IsItemClickEnabled="True"

ItemClick="ItemView_ItemClick">

<ListView.GroupStyle>

<GroupStyle>

<GroupStyle.HeaderTemplate>

<DataTemplate>

<Grid Margin="7,7,0,0">

<Button AutomationProperties.Name="Group Title"

Click="Header_Click"

Style="{StaticResource TextPrimaryButtonStyle}">

<StackPanel Orientation="Horizontal">

<TextBlock Text="{Binding Title}" Margin="3,-7,10,10"

Style="{StaticResource GroupHeaderTextStyle}" />

<TextBlock Text="{StaticResource ChevronGlyph}"

FontFamily="Segoe UI Symbol"

Margin="0,-7,0,10"

Style="{StaticResource GroupHeaderTextStyle}"/>

</StackPanel>

</Button>

</Grid>

</DataTemplate>

</GroupStyle.HeaderTemplate>

</GroupStyle>

</ListView.GroupStyle>

</ListView>

You might notice that the XAML for the ListView control is set up similar to the GridView control. You should use ListView for displaying content when limited space is available and in the snapped and full screen portrait view states.

The FlipView control

The FlipView control displays a list of items in a container with navigation controls that indicate the current position of the displayed data element within a collection. You can use this control when you expect users to be fully immersed in the content displayed, such as an image viewer app or a book reader app. In a touch-enabled device, the FlipView control provides a smooth transition between items when the user swipes in the left or right direction. Alternatively, you can click the forward and back buttons to navigate through the content and with a keyboard, the left and right arrow keys. Figure 3-26 shows the FlipView control used in the item details page in a Windows Store app created with the Grid App template in Visual Studio.

A screenshot of the item details page in a Windows Store app created with the Grid App template in Visual Studio shown in the FlipView control. Notice the forward and reverse buttons that appear when the user hovers the mouse over the screen.

Figure 3-26. The item details page in a Windows Store app created with the Grid App template in Visual Studio uses the FlipView control

The XAML sample code in Declaring and using the FlipView control shows how the FlipView control is declared and used in the item details page.

DECLARING AND USING THE FLIPVIEW CONTROL

<FlipView x:Name="flipView"

AutomationProperties.AutomationId="ItemsFlipView"

AutomationProperties.Name="Item Details"

TabIndex="1"

Grid.RowSpan="2"

ItemsSource="{Binding Source={StaticResource itemsViewSource}}">

<FlipView.ItemContainerStyle>

<Style TargetType="FlipViewItem">

<Setter Property="Margin" Value="0,137,0,0"/>

</Style>

</FlipView.ItemContainerStyle>

<FlipView.ItemTemplate>

<DataTemplate>

<!-- UserControl chosen as the templated item because

it supports visual state management. Loaded/unloaded

events explicitly subscribe to view state updates from the page -->

<UserControl Loaded="StartLayoutUpdates" Unloaded="StopLayoutUpdates">

<ScrollViewer x:Name="scrollViewer"

Style="{StaticResource HorizontalScrollViewerStyle}"

Grid.Row="1">

<!-- Content is allowed to flow across as many columns as needed -->

<!-- The RichTextColumns control provided by Visual Studio is used -->

<!-- VisualStateGroups for various view states -->

</ScrollViewer>

</UserControl>

</DataTemplate>

</FlipView.ItemTemplate>

</FlipView>

The XAML used to define a FlipView control uses a number of properties:

§ ItemsSource. This property specifies the CollectionViewSource used to data-bind the control.

§ DisplayMemberPath. This property specifies the name or path of the property that is displayed for each data item; this property is used with data binding.

§ ItemContainerStyle. This property specifies the style that is used when rendering the item containers.

§ ItemTemplate. This property sets the DataTemplate used to display each item.

Creating data templates to meet app requirements

Data controls such as GridView, ListView, and FlipView use data binding to display data in a collection. These controls require a “template” to specify the UI of each element in the collection when rendered on the screen. A DataTemplate is a section of the UI that is specified independent of the control it is used in. You can use one or more data templates with a data control if elements in your data collection cannot be represented with a single DataTemplate. Therefore, you can support complex layouts with a loose coupling between the data and the UI. It is a matter of updating the data template if the underlying data model changes for any reason.

In your Windows Store app, you might need to display the same data collection in multiple pages, perhaps in the same or different data control. Data templates are very helpful with reuse—you can define a DataTemplate within a ResourceDictionary available to the entire app. You could then use it in multiple pages. When you apply a data template to a data control, a data context is implicitly associated with it. This is through data binding. In many cases, raw data might not be adequate for displaying in the screen with data templates. In such cases, a viewmodel that acts as the data source can be used to customize the data. Because a data template is unaware of the underlying data context, whether it is a raw data source or a viewmodel, this technique helps with separation of concerns and reusing data templates, exactly what they are meant for.

In perhaps the simplest form, data templates are defined inline within the data control, such as in the ListView shown in the XAML in Defining data templates inline.

DEFINING DATA TEMPLATES INLINE

<ListView ItemsSource="{Binding Source={StaticResource officeMembers}}">

<ListView.ItemTemplate>

<DataTemplate>

<Grid Height="120" Margin="10">

<Grid.ColumnDefinitions>

<ColumnDefinition Width="Auto"/>

<ColumnDefinition Width="*"/>

</Grid.ColumnDefinitions>

<Border Width="120" Height="120">

<Image Source="{Binding MemberPhoto}" Stretch="None"/>

</Border>

<StackPanel Grid.Column="1" VerticalAlignment="Top" Margin="8,2,2,2">

<TextBlock Text="{Binding Name}"/>

<TextBlock Text="{Binding Designation"/>

<TextBlock Text="{Binding Phone}"/>

</StackPanel>

</Grid>

</DataTemplate>

</ListView.ItemTemplate>

</ListView>

In some Windows Store apps, you might need to display data based on the value of a property. For example, in Defining data templates inline, the data template cannot be used to differentiate between various kinds of team members in an organization. Your app might need to set a property of a UI element to highlight a certain category of team members—developers, for example. Windows provides the DataTemplateSelector class for implementing a template selection mechanism based on the data being bound to a data control. You need to implement your own template selector class, as shown in the C# code in Implementing a template selector class.

IMPLEMENTING A TEMPLATE SELECTOR CLASS

// Namespaces omitted for brevity

public class HighlightItemTemplateSelector : DataTemplateSelector

{

public DataTemplate DefaultTemplate { get; set; }

public DataTemplate HighlightTemplate { get; set; }

protected override DataTemplate SelectTemplateCore(object item,

DependencyObject container)

{

if (item != null &&

item is Person)

{

Person person = (Person)item;

if (person.Designation.ToLower().Contains("developer") ||

person.Designation.ToLower().Contains("engineer"))

{

return HighlightItemTemplate;

}

}

return DefaultTemplate;

}

}

The HighlightItemTemplateSelector class checks the item’s Designation property and returns the appropriate template. In the XAML, the two data templates are declared along with the template selector. To reuse data templates, consider putting them in the application’s resources in the App.xaml file. The ListView’s ItemTemplateSelector property is set to the template selector, as shown in Providing a template selector for a ListView control.

PROVIDING A TEMPLATE SELECTOR FOR A LISTVIEW CONTROL

<DataTemplate x:Key="ListView_DefaultItemTemplate">

<Grid Height="120" Margin="10">

<Grid.ColumnDefinitions>

<ColumnDefinition Width="Auto"/>

<ColumnDefinition Width="*"/>

</Grid.ColumnDefinitions>

<Border Width="120" Height="120">

<Image Source="{Binding MemberPhoto}" Stretch="None"/>

</Border>

<StackPanel Grid.Column="1" VerticalAlignment="Top" Margin="8,2,2,2">

<TextBlock Text="{Binding Name}"/>

<TextBlock Text="{Binding Designation"/>

<TextBlock Text="{Binding Phone}"/>

</StackPanel>

</Grid>

</DataTemplate>

<DataTemplate x:Key="ListView_HighlightItemTemplate">

<Grid Height="120" Margin="10">

<Grid.ColumnDefinitions>

<ColumnDefinition Width="Auto"/>

<ColumnDefinition Width="*"/>

</Grid.ColumnDefinitions>

<Border Width="120" Height="120">

<Image Source="{Binding MemberPhoto}" Stretch="None"/>

</Border>

<StackPanel Grid.Column="1" Background="Green"

VerticalAlignment="Top" Margin="8,2,2,2">

<TextBlock Text="{Binding Name}"/>

<TextBlock Text="{Binding Designation"/>

<TextBlock Text="{Binding Phone}"/>

</StackPanel>

</Grid>

</DataTemplate>

<local:HighlightItemTemplateSelector x:Key="listViewHighlightItemTemplateSelector"

DefaultTemplate="{StaticResource ListView_DefaultItemTemplate}"

HighlightTemplate="{StaticResource ListView_HighlightItemTemplate }" />

<ListView ItemsSource="{Binding Source={StaticResource officeMembers}}"

ItemTemplateSelector="listViewHighlightItemTemplateSelector" />

For an item in the collection that has “developer” or “engineer” in its Designation property, the HighlightTemplate will be used as the DataTemplate, and DefaultTemplate will be used in all other cases.

THOUGHT EXPERIMENT

Making design choices for a movie browser application

In this thought experiment, apply what you’ve learned about this objective. You can find answers to these questions in the “Answers” section at the end of this chapter.

A popular movie database and search engine website is about to provide access to their data through its public API. It expects developers to build applications on all major platforms, including Windows 8.

Armed with your experience in implementing Windows Store apps, you start the process of drawing up the requirements and wireframes of your app. With your knowledge of working with common data controls in Windows 8, list the five features you will implement in your app that will enable it to have an edge over the competition.

Objective summary

§ GridView, ListView, and FlipView are data controls with built-in support for interaction through touch and zoom. Visual Studio provides developers with application templates that are setup with these controls for displaying data.

§ The GridView control is used in UIs in which data is laid out horizontally. It can be scrolled and panned in the horizontal direction, so it is the ideal choice for supporting the fill and full screen landscape view states.

§ The ListView control is used in UIs with horizontal space constraints. It can be scrolled and panned in the vertical direction, so it is the ideal choice for supporting the snapped and full screen portrait view states.

§ The FlipView control should be used in distraction-free UIs such as photo albums and news readers. It has built-in support for the swipe gesture and supports accessibility through the keyboard and mouse.

§ Data templates provide the flexibility in the usage of data controls. They are used to compose the UI independent of the underlying data model. Data binding is used to connect the UI with view models with the data templates acting as the glue between the two.

§ The DataTemplateSelector class provides the capability to switch between multiple data templates in data controls. Templates are applied based on one or more conditions that are applicable on an item in the dataset.

Objective review

Answer the following questions to test your knowledge of the information in this objective. You can find the answers to these questions and explanations of why each answer choice is correct or incorrect in the “Answers” section at the end of this chapter.

1. You are building a page in an app that displays graphs of the user’s physical performance training program. A page can contain one or more graphs; the app does not expect the user to interact with the page other than browsing through the graphs using swipe gestures or the keyboard or mouse. The pages you build in the app will not be reused in the other apps. Which controls will you choose to create such a page? (Choose all that apply.)

a. A GridView control with variable sized items, one of them being the graph

b. A FlipView control that binds to the source data

c. RichTextBlock and RichTextBlockOverflow controls for displaying text

d. A grid to lay out the text and the graph in the DataTemplate of each item

e. A custom control that implements swipe gestures and embeds the graph and text

2. The local library has asked you to build a Windows Store app for its catalog. For the first release, it expects the app to display titles available in the library in a page with basic search functionality. The library also expects the app to be used by members of the library who use touch-enabled tablets, desktop PCs, and touch-enabled screen terminals on the library premises. Which controls will you use to meet the app’s requirements? (Choose all that apply.)

a. The FlipView control to swipe between pages of data

b. The GridView control to lay out data for the fill and full screen landscape view states

c. The ListView control to lay out data for the snapped and full screen portrait view states

d. The Grid control to lay out the data controls

e. The ListView control with a data template that uses the ScrollViewer control to scroll content horizontally

3. You have developed a Windows Store app that tracks the music albums a user has listened to, enabling the user to mark an album as a favorite. As an enhancement, you plan to implement a feature that highlights an album in the GridView when it is a favorite of the user. The pages you build in the app are specific to the requirements of the app and will not be reused in other apps. What is the best way to implement this feature?

a. Create a user control using the GridView. Implement template selection logic in the code-behind based on the data item.

b. Create your own DataTemplateSelector class along with two data templates: one for albums that are favorites and the other for albums that aren’t favorites. Based on the item, apply one template or the other with your DataTemplateSelector class.

c. Create a custom control with the ContentControl class as the base class. Implement your own logic to apply a template per the requirement.

d. Set the XAML to be displayed for a favorite item from within the code-behind.

Objective 3.5: Create and manage XAML styles and templates

In a Windows Store app, the UI is built with standard controls, and a set of custom and user controls is also used whenever necessary. XAML is used to declare various controls and define their properties in a page. To customize the look and feel of the controls in a page, the properties of various controls are set to meet the app’s requirements. This approach of composing a UI is powerful because it separates the UI from the underlying data model.

In a complex UI with a large number of controls, customizing the look and feel of each control using XAML becomes very tedious. In such scenarios, you want to define a set of styles that enable you to separate the values of properties of an element from the element itself. This approach is similar to using Cascading Style Sheets (CSS) to customize HTML elements in webpages. In Windows, the visual representation of a control is completely decoupled from its code. A control’s template defines the look and feel of the control, so the template can be modified while keeping the functionality of the control intact. In a Windows Store app, styles and templates are used to customize the appearance of controls.

NOTE

This objective covers how to:

§ Implement and extend styles and templates.

§ Implement gradients.

§ Modify styles based on event and property triggers.

§ Create shared resources and themes.

Implementing and extending styles and templates

The appearance of controls in a Windows Store app can be modified and customized to provide the look and feel of the UI per the app’s requirements. The Style property, represented by the Windows.UI.Xaml.Style class, is defined on FrameworkElement. The Style property can be used on UI elements that derive from the Control class, such as TextBlock and Button; as well as elements that don’t, such as Rectangle and Ellipse. You can create a style and apply it to a particular UI element in the XAML, or you can create it so it can be applied to all instances of the control.

Consider the example of a registration form that a Windows Store app uses to register a user for a service. The registration process requires some mandatory fields and includes some optional fields. The XAML in Declaring controls with mandatory and optional fields declares a few controls with their properties set to meet these requirements.

DECLARING CONTROLS WITH MANDATORY AND OPTIONAL FIELDS

<Grid Grid.Row="1" Margin="120,0,0,0">

<Grid.RowDefinitions>

<RowDefinition Height="Auto"/>

<RowDefinition Height="Auto" />

<RowDefinition Height="Auto"/>

<RowDefinition Height="Auto"/>

<RowDefinition Height="Auto"/>

<RowDefinition Height="Auto"/>

</Grid.RowDefinitions>

<StackPanel Orientation="Horizontal" Grid.Row="0" >

<TextBlock Foreground="Red" FontSize="24" Width="150"

Text="First Name" VerticalAlignment="Center" />

<TextBox FontSize="24" VerticalAlignment="Center" Width="200"

Margin="0,10,10,10"/>

</StackPanel>

<StackPanel Orientation="Horizontal" Grid.Row="1">

<TextBlock Foreground="Red" FontSize="24" Text="Last Name" Width="150"

VerticalAlignment="Center"/>

<TextBox FontSize="24" VerticalAlignment="Center" Width="200"

Margin="20,10,10,10"/>

</StackPanel>

<StackPanel Orientation="Horizontal" Grid.Row="2">

<TextBlock FontSize="24" Text="Gender" VerticalAlignment="Center" Width="150" />

<TextBox FontSize="24" Height="28" Margin="0,10,10,10" Width="200"

VerticalAlignment="Center" />

</StackPanel>

<StackPanel Orientation="Horizontal" Grid.Row="3">

<TextBlock Foreground="Red" FontSize="24" Text="Username" Width="150"

VerticalAlignment="Center"/>

<TextBox FontSize="24" VerticalAlignment="Center" Width="200"

Margin="0,10,10,10"/>

</StackPanel>

<StackPanel Orientation="Horizontal" Grid.Row="4">

<TextBlock Foreground="Red" FontSize="24" Text="Password"

VerticalAlignment="Center"/>

<TextBox FontSize="24" VerticalAlignment="Center" Width="200" Width="150"

Margin="0,10,10,10"/>

</StackPanel>

</Grid>

Figure 3-27 shows the controls rendered in the page.

A screenshot of an app named Controls Sample. The app displays several boxes with labels to the left: First Name, Last Name, Gender, Username, and Password.

Figure 3-27. An app with a set of TextBlock and TextBox controls with their properties set in XAML

In Declaring controls with mandatory and optional fields, some properties of the UI elements—such as Margin, Width, FontSize, and VerticalAlignment—are set at the same value across multiple times. You can create a style for the text blocks and another for the text boxes, and apply them as shown in the XAML in Applying styles for text blocks and text boxes.

APPLYING STYLES FOR TEXT BLOCKS AND TEXT BOXES

<Grid Grid.Row="1" Margin="120,0,0,0">

<Grid.RowDefinitions>

<RowDefinition Height="Auto"/>

<RowDefinition Height="Auto" />

<RowDefinition Height="Auto"/>

<RowDefinition Height="Auto"/

<RowDefinition Height="Auto"/>

<RowDefinition Height="Auto"/>

</Grid.RowDefinitions>

<Grid.Resources>

<Style x:Key="MandatoryTextBlockStyle" TargetType="TextBlock">

<Setter Property="Foreground" Value="Red" />

<Setter Property="FontSize" Value="24" />

<Setter Property="Width" Value="150" />

<Setter Property="VerticalAlignment" Value="Center" />

</Style>

<Style x:Key="RegistrationTextBoxStyle" TargetType="TextBox">

<Setter Property="FontSize" Value="24" />

<Setter Property="Margin" Value="0,10,10,10" />

<Setter Property="Width" Value="200" />

<Setter Property="VerticalAlignment" Value="Center" />

</Style>

</Grid.Resources>

<StackPanel Orientation="Horizontal" Grid.Row="0" >

<TextBlock Style="{StaticResource MandatoryTextBlockStyle}" Text="First Name" />

<TextBox Style="{StaticResource RegistrationTextBoxStyle}"/>

</StackPanel>

<StackPanel Orientation="Horizontal" Grid.Row="1">

<TextBlock Style="{StaticResource MandatoryTextBlockStyle}" Text="Last Name"/>

<TextBox Style="{StaticResource RegistrationTextBoxStyle}"/>

</StackPanel>

<StackPanel Orientation="Horizontal" Grid.Row="2">

<!-- You can create a new style for this TextBlock based on the

MandatoryTextBlockStyle and override the Foreground property in the

definition of the new style. However, since style will be required

in only one TextBlock, it is better to override the Foreground

property here. -->

<TextBlock Style="{StaticResource MandatoryTextBlockStyle}" Foreground="White"

Text="Gender" />

<TextBox Style="{StaticResource RegistrationTextBoxStyle}" />

</StackPanel>

<StackPanel Orientation="Horizontal" Grid.Row="3">

<TextBlock Style="{StaticResource MandatoryTextBlockStyle}" Text="Username" />

<TextBox Style="{StaticResource RegistrationTextBoxStyle}"/>

</StackPanel>

<StackPanel Orientation="Horizontal" Grid.Row="4">

<TextBlock Style="{StaticResource MandatoryTextBlockStyle}" Text="Password" />

<TextBox Style="{StaticResource RegistrationTextBoxStyle}"/>

</StackPanel>

</Grid>

In the XAML of a page, styles are declared with a unique key that is then used by UI elements. Windows looks for the Style definition in the parent element, then in the Page.Resources section of the Page that contains the XAML, and then in App.xaml, which can contain embeddedResourceDictionaries. In the TextBlock that is used as the label for the gender field, the Foreground property is set inline, overriding the value set through the Style. Therefore, you can override any property for a UI element set in the Style definition by specifying it inline.

Visual Studio provides styles for some UI elements such as the TextBlock. You can edit the built-in style of any control placed on an app’s design surface, create an empty style declaration and choose the properties of the control you plan to customize, or start with the default style of the control by selecting the Edit a Copy option. The last option creates a copy of the style in the page on which the control is placed, in App.xaml or in StandardStyles.xaml, which holds the app’s resource dictionary. These options are shown in Figure 3-28.

A screenshot of the Create Style Resource dialog box in Visual Studio. The selected options are Name (Key)/TextBlockStyle1 and Define in This document.

Figure 3-28. Visual Studio provides you with multiple options to place the Style resource in your application

If you plan to use the style in multiple pages of your app, you should create it in App.xaml or StandardStyles.xaml. If you plan to use the style within a single page, Visual Studio places the newly created Style resource within the Page.Resources section.

You can share the styles used for the TextBlock and TextBox controls in Figure 3-27 with other controls if their TargetType is set to Control. These styles can be defined without the Key, which causes the style to be applied for all controls of that TargetType. This is called an implicit style, in contrast with the styles discussed earlier that are explicit styles. For example, if you wanted all the TextBlock controls in a page to have some properties set to the same value, you can apply the following style in XAML:

<Style TargetType="TextBlock">

<Setter Property="FontSize" Value="24" />

<Setter Property="Width " Value="200" />

</Style>

The implicit style will be applied to all TextBlocks in a page if the style is declared in the Page.Resources section or it will be applied to all TextBlocks in your app if it is added with the ResourceDictionary section in App.xaml. Any TextBlock in the app can override the appearance set by the implicit style by explicitly setting individual properties of the Style. You can also apply the default style to a TextBlock in the app by setting its Style to null. An important property of the Style class is BasedOn. This property allows you create new styles based on existing styles referred using the StaticResource XAML extension. For example, the following code defines a style for the TextBlock control:

<Style x:Key="OptionalTextBlockStyle" TargetType="TextBlock"

BasedOn="{StaticResource MandatoryTextBlockStyle}">

<Setter Property="Foreground" Value="White" />

</Style>

The Style property of any control is useful in customizing its built-in appearance. You can change the built-in appearance of a control by using the ControlTemplate class to create a new style for the control. A ControlTemplate consists of a tree of elements that composes the control’s visual appearance. If you need to modify the appearance of a control, you can edit a copy of the control’s ControlTemplate (which is a part of its style) using Visual Studio. For some controls, such as ListView, you can edit and customize the ItemTemplate used to render an individual item.

After you have created a template for a control, you can reference it within the Style element in XAML and then apply the style on the control. For example, you might need to create a template for a button in your app. The button needs an icon added next to the text content. You can create a copy of the control template using Visual Studio, as shown in the XAML in Creating a copy of the control template.

CREATING A COPY OF THE CONTROL TEMPLATE

<Page.Resources>

<Style x:Key="UmbrellaButtonStyle" TargetType="Button">

<Setter Property="Background"

Value="{StaticResource ButtonBackgroundThemeBrush}"/>

<!-- Other Setters removed for brevity -->

<Setter Property="Template">

<Setter.Value>

<ControlTemplate TargetType="Button">

<Grid>

<VisualStateManager.VisualStateGroups>

<!-- Visual States for the Pressed, Disabled, Normal, etc -->

</VisualStateManager.VisualStateGroups>

<Border x:Name="Border" BorderBrush="{TemplateBinding BorderBrush}"

BorderThickness="{TemplateBinding BorderThickness}"

Background="{TemplateBinding Background}" Margin="3">

<ContentPresenter x:Name="ContentPresenter"

ContentTemplate="{TemplateBinding ContentTemplate}"

ContentTransitions="{TemplateBinding ContentTransitions}"

Content="{TemplateBinding Content}"

HorizontalAlignment="{TemplateBinding

HorizontalContentAlignment}"

Margin="{TemplateBinding Padding}"

VerticalAlignment="{TemplateBinding

VerticalContentAlignment}"/>

</Border>

<!-- Rectangles for the border drawn in some visual states -->

</Grid>

</ControlTemplate>

</Setter.Value>

</Setter>

</Style>

</Page.Resources>

Assuming you will not use this button elsewhere in your app, remove the border and use a StackPanel to lay out an Image and the ContentPresenter. The modified XAML is shown in Modifying the control template.

MODIFYING THE CONTROL TEMPLATE

<Page.Resources>

<Style x:Key="UmbrellaButtonStyle" TargetType="Button">

<Setter Property="Background"

Value="{StaticResource ButtonBackgroundThemeBrush}"/>

<!-- Other Setters removed for brevity -->

<Setter Property="Template">

<Setter.Value>

<ControlTemplate TargetType="Button">

<Grid>

<VisualStateManager.VisualStateGroups>

<!-- Visual States for the Pressed, Disabled, Normal, etc -->

</VisualStateManager.VisualStateGroups>

<StackPanel x:Name="Border" Orientation="Horizontal"

Background="{TemplateBinding Background}" Margin="3">

<Image Source="Assets/umbrella.png" Height="30" Width="30"

Stretch="Uniform" Margin="10,0,0,0" />

<ContentPresenter x:Name="ContentPresenter"

ContentTemplate="{TemplateBinding ContentTemplate}"

ContentTransitions="{TemplateBinding ContentTransitions}"

Content="{TemplateBinding Content}"

HorizontalAlignment="{TemplateBinding

HorizontalContentAlignment}"

Margin="{TemplateBinding Padding}"

VerticalAlignment="{TemplateBinding

VerticalContentAlignment}"/>

</StackPanel>

<!-- Rectangles for the border drawn in some visual states -->

</Grid>

</ControlTemplate>

</Setter.Value>

</Setter>

</Style>

</Page.Resources>

Figure 3-29 shows two buttons, first with its default style, and second with its style set to UmbrellaButtonStyle.

A screenshot of two buttons with the same text: Press Here. The first button uses the default style, and the second button uses a customized style, which displays an umbrella on the left side of the button.

Figure 3-29. The first button uses the default style; the second button uses a customized control template set in its style

If you plan to use the button’s style elsewhere in your app with other icons, you can reuse the ControlTemplate for the Button by specifying a binding for the Source property of the image. When you define the button in the XAML of the page, the Source property of the Image can be set through the Binding.

You can use the ControlTemplate to define the visual structure of a button. The default template of a control also specifies the visual behavior of the control, that is, the appearance of the control in various states. For example, a button can be in the PointerOver, Pressed, Disabled, Focused, Unfocused, and PointerFocused states. A visual state is represented by the VisualState class; thus, a ControlTemplate contains a number of VisualState objects, each representing a visual state. A VisualState contains a StoryBoard animation that changes the appearance of elements in theControlTemplate. The StoryBoard of a VisualState begins when the control enters the state specified by the Name property of the VisualState object. One or more VisualState objects belong to a VisualStateGroup, and one or more VisualStateGroup objects are added to theVisualStateManager.VisualStateGroups element, which is set at the root element of the ControlTemplate.

Implementing gradients

The controls provided by Windows and used in Windows Store apps have a Background or Fill property to create a solid color. This gives the UI a flat look. In some cases, you might want to add a soft gradient in the controls to improve the user experience of your app. For example, you want to add a three-dimensional look to some or all the buttons in a page. It is possible to use bitmap images to achieve this; however, there are advantages of using gradients:

§ Animations are supported by gradients. Therefore, you can change a gradient’s colors for a certain user action; for example, when they press a button with a gradient as the background.

§ A gradient is not prone to loss of quality with scale because it is used on vector graphics, unlike an image.

§ Gradients use hardware acceleration when it is available.

§ The size of your application is less because you do not have to embed bitmap images for the background.

Thus, gradients provide better performance than images. However, carefully consider the use of gradients in app controls. Gradients can be distracting when used too often on a page. It’s better to use a gradient to highlight a particular control, which draws the attention of the user.

You can define gradients in the XAML for a control and use them for setting the value of the Background or Fill property of the control. The XAML in Defining LinearGradientBrush as a resource and using it in a Rectangle control shows a LinearGradientBrush defined as a resource for the page and later used in a Rectangle control.

DEFINING LINEARGRADIENTBRUSH AS A RESOURCE AND USING IT IN A RECTANGLE CONTROL

<Page>

<Page.Resources>

<LinearGradientBrush x:Key="BlueGradientBackground"

StartPoint="0.5,0" EndPoint="0.5,1">

<GradientStop Color="#FFEBF9FF" Offset="0"/>

<GradientStop Color="#FF008BC7" Offset="1"/>

<GradientStop Color="#FF00B8FF" Offset="0.20"/>

<GradientStop Color="#FF00B3FF" Offset="0.90"/>

</LinearGradientBrush>

</Page.Resources>

<Grid>

<Grid.RowDefinitions>

<RowDefinition Height="Auto" />

<RowDefinition Height="*" />

</Grid.RowDefinitions>

<StackPanel Grid.Row="6" Orientation="Horizontal">

<Rectangle Width="170" Height="65" Margin="10"

HorizontalAlignment="Left" Fill="#FF00B8FF" />

<Rectangle Width="170" Height="65" Margin="10"

HorizontalAlignment="Left"

Fill="{StaticResource BlueGradientBackground}" />

</StackPanel>

</Grid>

</Page>

Figure 3-30 shows the two rendered rectangle controls.

A screenshot showing two medium-blue rectangles, side by side. The rectangle on the left uses a solid color to fill its area, which provides a flat appearance. The rectangle on the right has a gradient applied, from lighter (top) to darker (bottom).

Figure 3-30. Using a gradient as the Background or Fill property of a control achieves a three-dimensional appearance in the rectangle on the right

Modifying styles based on event and property triggers

The values of various properties of a control set through a style or a control template you created might require updates when certain conditions are met. For example, when a button is pressed, you want the color of the foreground to change.

Unlike technologies such as Windows Presentation Foundation (WPF) and Silverlight, in which triggers can be used to modify styles and control templates, Windows 8 provides the VisualStateManager to manage these changes. The VisualStateManager is responsible for managing visual states and the transitions between these states for controls. The VisualStateGroups element is used to define the visual states of a control in XAML. Alternatively, the GoToState method of the VisualStateManager class is used to transition between the various states of a control in the code-behind of the page that contains the control.

Visual state groups and visual states defined in a control template shows the XAML for VisualStateGroups and the VisualStates of a button defined in its ControlTemplate.

VISUAL STATE GROUPS AND VISUAL STATES DEFINED IN A CONTROL TEMPLATE

<VisualStateManager.VisualStateGroups>

<VisualStateGroup x:Name="CommonStates">

<VisualState x:Name="Normal"/>

<VisualState x:Name="PointerOver">

<Storyboard>

<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background"

Storyboard.TargetName="Border">

<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource

ButtonPointerOverBackgroundThemeBrush}"/>

</ObjectAnimationUsingKeyFrames>

<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground"

Storyboard.TargetName="ContentPresenter">

<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource

ButtonPointerOverForegroundThemeBrush}"/>

</ObjectAnimationUsingKeyFrames>

</Storyboard>

</VisualState>

<VisualState x:Name="Pressed">

<Storyboard>

<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background"

Storyboard.TargetName="Border">

<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource

ButtonPressedBackgroundThemeBrush}"/>

</ObjectAnimationUsingKeyFrames>

<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground"

Storyboard.TargetName="ContentPresenter">

<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource

ButtonPressedForegroundThemeBrush}"/>

</ObjectAnimationUsingKeyFrames>

</Storyboard>

</VisualState>

<VisualState x:Name="Disabled">

<Storyboard>

<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background"

Storyboard.TargetName="Border">

<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource

ButtonDisabledBackgroundThemeBrush}"/>

</ObjectAnimationUsingKeyFrames>

<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush"

Storyboard.TargetName="Border">

<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource

ButtonDisabledBorderThemeBrush}"/>

</ObjectAnimationUsingKeyFrames>

<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground"

Storyboard.TargetName="ContentPresenter">

<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource

ButtonDisabledForegroundThemeBrush}"/>

</ObjectAnimationUsingKeyFrames>

</Storyboard>

</VisualState>

</VisualStateGroup>

<VisualStateGroup x:Name="FocusStates">

<VisualState x:Name="Focused">

<Storyboard>

<DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity"

Storyboard.TargetName="FocusVisualWhite"/>

<DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity"

Storyboard.TargetName="FocusVisualBlack"/>

</Storyboard>

</VisualState>

<VisualState x:Name="Unfocused"/>

<VisualState x:Name="PointerFocused"/>

</VisualStateGroup>

</VisualStateManager.VisualStateGroups>

In the code-behind of a page, an event handler can be defined for an event such as when the mouse hovers over a button or when it is clicked. To prevent the user from continuously clicking the button after it has been clicked once, you should provide a disabled look to the button and prevent further click events until an action is complete. The GoToState method of the VisualStateManager class can be used to transition between states configured in the ControlTemplate of the button. In the code-behind of the page, use the Clicked event handler of the button to change its visual appearance by applying a style that resembles a disabled button.

Creating shared resources and themes

While building a Windows Store app, you can reuse the styles and control templates you create to customize the visual appearance of controls. Collections of styles and control templates can be defined for the application in resource dictionary. You can create a resource dictionary using Visual Studio with the Add New Item option for your project, as shown in Figure 3-31.

A screenshot of the Add New Item dialog box in Visual Studio. Windows Store is selected in the Visual C# tree on the left. Resource Dictionary is selected in the middle pane. The new item is being name MyDictionary.xaml in the Name box at the bottom of the dialog box.

Figure 3-31. Adding a resource dictionary with Visual Studio

You add the newly created resource dictionary to your app by specifying it in the list of application resources in App.xaml, as follows:

<Application.Resources>

<ResourceDictionary>

<ResourceDictionary.MergedDictionaries>

<ResourceDictionary Source="Common/StandardStyles.xaml"/>

<ResourceDictionary Source="MyDictionary.xaml" />

</ResourceDictionary.MergedDictionaries>

<x:String x:Key="AppName">Grid App Sample</x:String>

</ResourceDictionary>

</Application.Resources>

Windows Store project templates provided by Visual Studio specify the default styles of controls within a resource dictionary defined in the StandardStyles.xaml file. The ResourceDictionary class defines a dictionary of objects that are shareable across your app. ResourceDictionary supports styles and templates, brushes and colors, animations including StoryBoard, transforms, and other objects Resources from the ResourceDictionary are accessed with the StaticResource XAML extension.

You can merge multiple resource dictionaries into a single resource dictionary and use it in your app. A theme dictionary can define a dictionary of objects depending on the theme currently selected by the user. Each object in this dictionary is a ResourceDictionary with a unique key. The following XAML shows two themes defined with ResourceDictionary objects and included within the ThemedDictionaries collection:

<Application.Resources>

<ResourceDictionary>

<ResourceDictionary.ThemeDictionaries>

<ResourceDictionary x:Key="Default">

<SolidColorBrush

x:Key="ButtonBackground">#FF000000</SolidColorBrush>

</ResourceDictionary>

<ResourceDictionary x:Key="Light">

<SolidColorBrush

x:Key="ButtonBackground">#FFCCDDCC</SolidColorBrush>

</ResourceDictionary>

</ResourceDictionary.ThemeDictionaries>

<ResourceDictionary.MergedDictionaries>

<ResourceDictionary Source="Common/StandardStyles.xaml"/>

<ResourceDictionary Source="MyDictionary.xaml" />

</ResourceDictionary.MergedDictionaries>

<x:String x:Key="AppName">Grid App Sample</x:String>

</ResourceDictionary>

</Application.Resources>

A theme defined as a ResourceDictionary can be applied in an application using the RequestedTheme property of the Application class, as shown in the following XAML:

<Application x:Class="GridAppSample.App" RequestedTheme="Light">

</Application>

THOUGHT EXPERIMENT

Supporting themes in a Windows Store app

In this thought experiment, apply what you’ve learned about this objective. You can find answers to these questions in the “Answers” section at the end of this chapter.

You have developed an app used for educating children in primary school. The app has received good feedback as well as feature requests.

One feature request is to enable users to choose a theme based on a movie, fable, or fairy tale. You decide to enhance your app and implement support for themes. Which three Windows 8 features will you use to implement the feature request?

Objective summary

§ Windows provides styles and templates for customizing the visual appearance and behavior of controls. They can be reused across multiple pages in an application. Visual Studio can be used to edit a copy of the style or template of a control.

§ In some applications, a gradient applied to a control can draw the attention of the user for a particular task. Gradients have a number of advantages over images, mainly in performance and scaling to multiple screen resolutions.

§ The visual states of a control are managed with the VisualStateManager class. VisualStateGroups is used to define the various states in which a control can exist. The GoToState method of the VisualStateManager can be used to change between various states of a control based on events of the control.

§ Resource dictionaries can be used to specify sets of styles and templates. These dictionaries can then be included in the application. ThemedDictionaries are used to define themes that can be selected based on user preferences.

Objective review

Answer the following questions to test your knowledge of the information in this objective. You can find the answers to these questions and explanations of why each answer choice is correct or incorrect in the “Answers” section at the end of this chapter.

1. Due to a change in requirements, a Windows Store app you developed requires an update. The UI displays a list of items from a remote web service from which the user can select one or more items and carry out some operations. After the update, the app is expected to highlight the buttons that the user clicks to perform the operations. You are not likely to use this feature in other Windows Store apps you will build. How will you implement this requirement?

a. Create a user control based on the Button class. Replace the buttons with this new user control.

b. Create a custom control and package it in an assembly. Use this control to implement the requirement.

c. Create a new style for the buttons with the Background property set to a LinearGradientBrush that makes the appearance of the button more prominent.

d. Replace the buttons with the ToggleSwitch control. An operation is performed if the user sets the ToggleSwitch to On.

2. While building a Windows Store app, you realize you are specifying the properties of some controls in every page. You want to have clean and simple XAML with maximum reuse of the XAML within the app you have written. What steps should you take? (Choose all that apply.)

a. Create styles for these controls and place them in the page where they are required.

b. Create implicit styles wherever possible and include properties set with the same value across multiple pages.

c. Create styles for the controls and set the properties that are common across multiple declarations of the control.

d. Create a resource dictionary and include it in the application level. Use the resource dictionary to define new styles so they are available throughout the app.

e. Create custom controls and set the properties in the code-behind.

3. Users have reported that some UI elements in your app are barely visible in bright light conditions. You decide to update your app to address the problem. What is the best way to address this problem and implement a solution without updating the entire app?

a. Create a set of styles and control templates that help the user view the app’s controls in bright light. Update each page of your app to apply these newly created styles and templates.

b. Create a set of themes optimized for various light conditions, such as bright light and dark interiors, and include them in the ThemedDictionaries section in the App.xaml file. Allow the user to select a theme through the Settings charm.

c. Create sets of styles and templates for various light conditions. Detect the ambient light using the proximity sensor and apply these resources throughout the app.

d. Build a version of your app specifically for bright light conditions and make it available through the Windows Store.

Chapter summary

§ Any Windows Store app can be used in a variety of devices with different screen sizes and resolutions. You should develop your app such that it renders well on all screens. Based on your app’s core features, you can restrict the orientations supported in the app by selecting a specific orientation in the package manifest.

§ The Grid control can create a flexible and fluid layout. In situations where content is likely to overflow the visible area, use the ScrollViewer control.

§ For displaying content with pictures or hyperlinks, for example, consider using the RichTextBlock control with the RichTextBlockOverflow companion control.

§ The top app bar provides navigation among various sections of an app.

§ The bottom app provides access to commands that are in-context with the page currently being viewed by the user.

§ Avoid too many commands in the app bar and consider using a context menu instead. Place commands you expect to be used frequently toward the edges of the app bar.

§ To display lists of data, use the GridView, ListView, and FlipView controls. These controls have built-in touch support and should be used based on the type of data to be displayed.

§ Data templates provide flexibility with data controls in displaying data without the detailed knowledge of the underlying data model. The DataTemplateSelector class applies data templates selectively.

§ Styles and control templates can be used to customize the visual appearance of controls. Gradients are helpful in drawing the attention of users towards certain actions.

§ The VisualStateManager class can be used with VisualStateGroups element in XAML to define various states a control can exist. The GoToState method can be used to change between various states.

§ You can create resource dictionaries and use them in your app to customize the appearance of various controls. Themes with one or more resource dictionaries can be used to provide a consistent look and feel in your app.

Answers

This section contains the solutions to the thought experiments and the answers to the lesson review questions in this chapter.

Objective 3.1: Thought experiment

1. Use layout controls. The layout controls provided by Microsoft, such as Grid, help build a fluid layout, which helps provide a consistent user experience across various devices and screens.

2. Design for touch, support keyboard and mouse­. The app must support users with touch-enabled devices as well as input from a keyboard and mouse.

3. Support multiple orientation and screen sizes. To improve the user experience, your app should support multiple orientations and various screen sizes.

Objective 3.1: Review

1. Correct answers: A, B, C

a. Correct: Windows supports the full screen view state in landscape orientation.

b. Correct: Windows supports the fill view state in landscape orientation.

c. Correct: Windows supports the snapped view state in landscape orientation.

d. Incorrect: Windows supports the snapped view state in the landscape orientation only; the snapped view state is not supported in the portrait orientation.

e. Incorrect: Windows supports the fill view state in the landscape orientation only; the fill view state is not supported in the portrait orientation.

2. Correct answer: C

a. Incorrect: Implicit transitions update properties that are a Double, Color, or Point value, with animations. Using implicit transitions is not enough to meet the requirement.

b. Incorrect: Explicit transitions are applied on properties such as Length and Width, usually with animations.

c. Correct: The VisualStateManager with VisualStates for the supported view states is the preferred way to implement this requirement. Properties of individual UI elements are not altered; instead, they are invisible after the transition to a different orientation.

d. Incorrect: The constructor is invoked when the page is created, so the app will not respond to changes in its orientation after it is visible. The VisualStateManager should be used in the OnSizeChanged event of the page to update its layout.

3. Correct answers: A, B, D

a. Correct: Your app might not support all the orientations that the device can be in. You should declare the supported orientations in the package manifest.

b. Correct: The VisualStateManager can be used to swap visual states defined in the XAML of a page. Each visual state usually represents the layout for a certain view state.

c. Incorrect: The OnLaunched event is fired only once when the application is launched by the user. To update the view state of a page, the visual state should change after the page is visible and when the user changes the orientation.

d. Correct: The OnSizeChanged event is fired whenever the height and width of a page changes; for example, when the user changes the device’s orientation. The VisualStateManager can be used to update the layout of the page.

e. Incorrect: The constructor of a page runs only once, when the page is created. However, users can change the orientation of their device while using your application. The OnSizeChanged event should be used to update the visual state.

Objective 3.2: Thought experiment

1. Built-in support for touch. It is easier to manipulate 3D models on a multi-touch monitor. The organization will benefit from built-in touch support in the controls provided by Windows.

2. Built-in support for zoom. ­In many uses, zooming into a 3D model is necessary. Windows 8 controls have built-in support for zoom.

3. Same user experience across multiple screen sizes­. The app is likely to be used in the manufacturing division on tablets. Therefore, users might find it convenient to use the app with zoom through touch interactions.

Objective 3.2: Review

1. Correct answer: B

a. Incorrect: Creating styles and templates for each orientation makes it difficult to use them.

b. Correct: Star sizing of rows and columns in a grid uses the available dimensions of the page and distributes the available area proportionally among the rows and columns. Styles and templates should be used for various view states to adjust the size of the controls.

c. Incorrect: A layout you create needs to support various orientations, view states, a mechanism to arrange controls, and so on. The Grid control implements this functionality and provides additional features.

d. Incorrect: A user might not know more content exists and that they need to swipe through all items in that page.

2. Correct answers: B, C, D

a. Incorrect: A custom control needs to implement support for various orientations and view states, layout of controls in the page, and so on. The Grid control provides this functionality and is recommended for laying out a page.

b. Correct: A RichTextBlock control should be placed in the root layout element and used along with RichTextBlockOverflow controls to allow text to overflow.

c. Correct: You can use columns with star sizing to lay out a RichTextBlock control along with one or more RichTextBlockOverflow controls to render overflowing text.

d. Correct: The RichTextBlockOverflow control and the RichTextBlock control display overflow text.

e. Incorrect: The fundamental problem is choosing the right layout method across multiple view states and therefore, using styles and templates only will not solve the problem.

3. Correct answers: A, D, E

a. Correct: The Grid control supports fluid layouts and easily adapts to orientation changes. Start sizing distributes available area proportionally among rows and columns.

b. Incorrect: Although the Grid control is a popular control for creating layouts, you can also use the Canvas and StackPanel controls as layout controls.

c. Incorrect: ScrollViewer supports horizontal and vertical scrolling.

d. Correct: The ScrollViewer control has built-in support for touch-enabled devices. Therefore, users can interact with content rendered within a ScrollViewer through touch gestures.

e. Correct: The ScrollViewer control automatically adds vertical and/or horizontal scrollbars whenever content overflows the visible area of the screen.

Objective 3.3: Thought experiment

1. Search and share are implemented in a Windows Store app using their respective charms. The app bar provides commands relevant for a page in the app.

2. The user can use the top app bar to navigate to a section instead of returning to the hub page and navigating from there.

3. You can use Styles and VisualStates to customize the buttons in the app bar and (optionally) their layout.

Objective 3.3: Review

1. Correct answers: A, C, D

a. Correct: Search within the page can be implemented as a button in the app bar that, when pressed, opens a search box for searching the text.

b. Incorrect: Cut, copy, and paste should be implemented in a context menu visible when the user has selected some text.

c. Correct: The user is likely to change the font size occasionally, so these commands should be placed in the app bar.

d. Correct: The user is likely to create, edit, and delete files when an existing file is open in the app. Therefore, these commands should be placed toward the left edge of the app bar.

e. Incorrect: The recommended way to share a file from within an app is to use the Share charm.

2. Correct answers: A, B, D

a. Correct: You can create a button for the app bar using the hexadecimal character of a font symbol obtained with the Character Map tool.

b. Correct: You can use an image as the content of a button in the app bar.

c. Incorrect: If you do not set the content of a button in the app bar, it will not help the user identify it.

d. Correct: You can convert an image or icon into an XAML path and use it in a button for the app bar.

e. Incorrect: The device might not be connected to the Internet, in which case a button in the app bar that uses an Internet resource will not provide visual guidance to the user.

3. Correct answers: A, B, C

a. Correct: The Loaded event is fired after the app bar is available for interaction in the app. Therefore, the app should subscribe for layout update events in the event handler of the Loaded event.

b. Correct: The UnLoaded event is fired after the app bar is dismissed. The app should unsubscribe for layout update events in the event handler of the UnLoaded event.

c. Correct: Setting IsSticky for the app bar to True ensures it is visible even when the actions such as tap on the surface to hide the app bar are carried out.

d. Incorrect: The Opened event is fired after the app bar is created and is visible in the page.

e. Incorrect: The Closed event is fired when the app bar is no longer visible in the page.

Objective 3.4: Thought experiment

1. Smooth, fluid layout. You can use the Grid control to create a smooth and fluid layout that adapts to various view states.

2. Sophisticated data controls. GridView and ListView provide users with an easy-to-use interface to browse through lists.

3. Distraction-free experience. A FlipView control enables users to browse through the catalog in which they’re viewing an item.

4. Frequently used controls in one location. The app bar provides in-context access to controls, letting the user focus on content.

5. Multiple view state support. Your app is likely to be used more often if it supports the snapped view state and even the full screen portrait view state. Users might often snap your app and use it with other apps or they might decide to read movie reviews in portrait mode.

Objective 3.4: Review

1. Correct answers: B, C, D

a. Incorrect: Each page has a limited amount of data that can be displayed using layout controls such as Grid.

b. Correct: The FlipView control displays a list of items without showing other items in the list. Users can view various graphs in this control while flipping through the list.

c. Correct: The RichTextBlock and RichTextBlockOverflow controls are useful for rendering text whose length is unknown. They can be used in various orientations while laid out in a Grid control.

d. Correct: A grid is suitable for laying out a graph and associated text using the RichTextBlock and RichTextBlockOverflow controls.

e. Incorrect: You should develop a custom control only when you expect to use it in other Windows Store apps as well.

2. Correct answers: B, C, D

a. Incorrect: The FlipView control displays item details for a list of items.

b. Correct: The GridView control is suitable for laying out items horizontally in the screen.

c. Correct: The ListView control is suitable for laying out items vertically in the screen.

d. Correct: The Grid control can be set up with star sizing to lay out data controls.

e. Incorrect: The ListView control is recommended for layouts that take advantage of vertically scrolling through a list of items, such as the snapped and full screen portrait view states.

3. Correct answer: B

a. Incorrect: A user control will require modifications whenever there is a change in the requirements, such as addition of a new template for the items in the GridView.

b. Correct: The DataTemplateSelector class can be used with the GridView control to apply a specific data template to an item based on the item’s value.

c. Incorrect: You should use a custom control when you plan to implement the same feature in multiple Windows Store apps.

d. Incorrect: A code-behind approach means strong coupling between the UI and the business logic, which can cause maintenance problems in the future.

Objective 3.5: Thought experiment

1. Use styles, control templates, and visual states to customize controls as much as possible, with a view to reuse them across a page and within the app.

2. Use the VisualStateManager class to implement updates in the properties of controls whenever necessary.

3. Use multiple resource dictionaries to implement themes and make them all available to the user.

Objective 3.5: Review

1. Correct answer: C

a. Incorrect: A user control created to implement the requirement might need modification if requirements change.

b. Incorrect: A custom control is typically used to implement a fundamental requirement across a number of apps and share the XAML and code across multiple pages in more than one app. In this case, the requirement is specific to the app and does not justify creation of a custom control.

c. Correct: Styles defined in XAML allow for decoupling of the UI from the business logic. Therefore, any future updates can be carried out with ease.

d. Incorrect: The ToggleSwitch control is used to apply any one of two values for a property. Therefore, it might confuse the user if it is used to highlight an action.

2. Correct answers: B, C, D

a. Incorrect: Styles in a page are available for controls within the page only. This minimizes their use across multiple pages in an app.

b. Correct: Implicit styles created for a specific control are applied on all instances of the control in an app.

c. Correct: When a property of a control is set to the same value multiple times in an app, it can be set through a style that is applied on all instances of that control. Implicit styles are suitable in such cases.

d. Correct: Styles defined in a resource dictionary are available throughout the application.

e. Incorrect: Custom controls are created to implement a set of requirements that are applicable to a number of apps. For example, they are useful for branding a set of apps. Therefore, custom controls are not suitable when the XAML is reused within a Windows Store app.

3. Correct answer: B

a. Incorrect: If you update the styles and templates in your app to improve the user experience in bright light conditions, you might have problems in other lighting conditions.

b. Correct: Themes consist of a group of styles and templates suitable for a set of requirements, such as bright light, low light, and dark light. The user will find it convenient to select a theme based on lighting conditions.

c. Incorrect: Not all user devices contain the proximity sensor.

d. Incorrect: Creating a separate version of your app that supports bright light means you have to support multiple versions of your app, and you might need to create versions for other lighting conditions.