Enhance the user experience - Build Windows® 8 Apps with Microsoft® Visual C#® and Visual Basic® Step by Step (2013)

Build Windows® 8 Apps with Microsoft® Visual C#® and Visual Basic® Step by Step (2013)

Chapter 7. Enhance the user experience

After completing this chapter, you will be able to

§ Draw an application using Microsoft Visual Studio 2012 visual tools.

§ Create an application layout.

§ Customize the appearance of controls.

Understanding the XAML layout system is fundamental to position and arrange elements in a Windows Store app. The base class for all elements that provide layout support is Panel and the platform includes a suite of derived panel classes that enable many complex layouts. This chapter provides an introduction to the available layout Panel elements.

Styling and templating refer to a suite of features that allow developers and designers to create visually compelling effects and to create a consistent appearance for their applications. Another feature of the XAML styling model is the separation of presentation and logic. This means that designers can work on the appearance of an application by using only XAML at the same time that developers work on the programming logic using C# or Visual Basic (VB). This chapter focuses on the styling and templating aspects of the application.

Draw an application using Visual Studio 2012

Visual Studio 2012 contains many different tools to create a Windows Store app graphically and interactively.

In the introductory section of this chapter, you will learn how to use the Visual Studio 2012 designer in order to add controls to the page structure and customize the properties using the appropriate graphic palettes.

Create a graphical application in Visual Studio 2012

1. Create a new Application project. To do that, open Visual Studio 2012, and from the File menu, select New Project (the sequence can be File | New | Project for full-featured versions of Visual Studio). Choose Visual C# from the Templates tree and then Windows Store from the list of installed templates. Finally, choose the Blank App (XAML) project type from the list of available projects.

2. Select version 4.5 as the .NET Framework version for your new project.

3. Name the new project Panels, and then choose a location on your file system and a solution name. When you’re finished, click OK. As you saw in Chapter 3, the Windows Store application template provides a default page (MainPage.xaml), an application entry point in the App class (App.xaml.cs), a default application description and a declaration in the Package.appxmanifest file, as well as four default images representing logos and a splash screen.

4. In the Solution Explorer, double-click the MainPage.xaml file.

This file contains the layout of the user interface. The window, named Design View, shows two different views of the file.

image with no caption

The top panel, named Design, contains the graphical display of the page, whereas the bottom panel, named XAML, shows the XAML code of the same page.

In the next procedure, you will use the Design View window to add a control to the user interface of an application and customize some of its properties using the designer and the Properties window.

Create the user interface

1. Click the Toolbox tab that appears on the left of the form in the Design View window.

2. Expand the Common XAML Controls section.

This section contains the most common controls; you can click the All XAML Control section to visualize the full list of controls provided by the platform.

3. In the Common XAML Controls section, drag the TextBlock control onto the page.

TIP

If you dragged a different control, you can delete it from the page by selecting the item within the design area and clicking Delete.

This operation creates a TextBlock control within the page and the Toolbox disappears temporarily. If you want the Toolbox to always be visible, just click Auto Hide on the right-hand side of the title bar.

TIP

The thumbtack (push pin) provides a visual cue as to whether the Toolbox (or any other window for that matter) will automatically hide itself when not in use.

Click the TextBlock control in the form and drag it wherever you prefer. Notice that you may need to click away from the control and then click it again before the Design View window allows you to move it.

The bottom panel of the Design View contains the markup code of the layout you have just created. It includes a description of a TextBlock control with its properties: Margin, Text, HorizontalAlignment, and VerticalAlignment.

The XAML code of the TextBlock control should look like the following:

<TextBlock HorizontalAlignment="Left" Height="54" Width="250" Margin="216,171,0,0"

TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top"/>

The Margin property may be different depending on where you placed the control on the page, such as the Height and the Width properties that depend on your actions on the designer. The XAML pane and the Design View window have a two-way relationship. You can edit the XAML code from the XAML pane and see the changes reflected in the Design View window, and vice versa. Practice changing the Margin property in the XAML panel. You will notice a visual change in the position of the control in the Design View window.

4. On the View menu, click Properties.

It is possible to set any property by using the XAML code, but it is definitely easier to use the Properties window for this task. The Properties window shows the properties of the currently selected control; in fact, if you click the TextBlock control in the Design View window, you’ll see the properties of that control. However, if you click outside the TextBlock you will notice the Properties window displaying the properties of the parent Grid.

5. Click the TextBlock control in the Design View window. The Properties window will display the properties for the TextBlock control again.

6. In the Properties window, expand the Text property and change the FontSize property to 16 px. This property is located next to the drop-down list box containing the name of the font.

7. In the XAML pane below the Design View window, examine the text that defines the TextBlock control. If you scroll to the end of the line, you should see the text FontSize=“16”. Changes performed using the Properties window will be reflected in the XAML source code automatically and, consequently, also in the Design View window.

8. Set the value of the FontSize property in the XAML panel to 24; you will notice a visual change in the Design View window, as well as a change in the drop-down list box of the Properties window.

9. Open the Common section of the Properties window and change the value of the Text property from TextBlock to Hello Windows 8 App!

NOTE

If you choose to organize the property names in alphabetical order, you will not find the Common section or any other categories, so you have to find the property in the list (the Text property in this case) and change its value as described in the procedure.

10.On the Build menu, click Build Solution, and verify that the project builds successfully.

11.On the Debug menu, click Start Debugging.

image with no caption

12.Return to Visual Studio 2012 by pressing ALT+TAB. On the Debug menu, click Stop Debugging.

Create the layout of a Windows 8 application

The objects derived from the Panel class are responsible for the placement of controls. These objects act as containers of user interface elements, and each of them has its specificities and behaviors. In this section, you will learn them and use them from within a Windows 8 application.

Use the Canvas panel

The aim of the Canvas control is to place its child elements through coordinates that are relatives to the parent Canvas.

1. Create a new Application project. To do that, open Visual Studio 2012 and, from the File menu, select New Project. Choose Windows Store from the list of installed templates, and then choose Blank App (XAML) from the list of available projects.

2. Select version 4.5 as the .NET Framework version for your new project.

3. Name the new project Canvas, and then choose a location on your file system and a solution name. When you’re finished, click OK.

4. Click the Toolbox tab that appears in the left-hand side of the form in the Design View window.

5. Expand the All XAML Controls section.

6. Click the Canvas control and drag it within the form.

7. Using the designer surface, modify the dimensions and position of the Canvas control until you get something that resembles the following graphic.

image with no caption

8. From the Toolbox tab, choose a Button control and drag it within the existing Canvas.

9. Modify the Margin, Height, and Width properties as you like.

10.Repeat steps 8 and 9 two more times to obtain a total of three Button controls contained within the Canvas panel. The following graphic shows a possible composition of the above-mentioned controls, but feel free to express your creativity by arranging them in different orders or modifying their dimensions.

image with no caption

11.Click any of the three Button controls in the Design View window.

12.In the Properties window, expand the Layout category and modify the Left property by setting a higher value. You will notice a change in the placement of the selected control.

13.In the XAML panel, take a look at the source code of the Button controls. In addition to the classic properties, you can see the new properties Canvas.Left and Canvas.Top.

These properties are also called “attached properties” because they do not belong to the object model of the target element, but are rather “attached” to the control itself by the parent control. Their purpose is to provide an indication to the parent panel about the position of the control. In our scenario, the Canvas panel exposes the attached Canvas.Left and Canvas.Top properties; their role is to allow the absolute positioning of the child controls.

NOTE

The Canvas.Left and Canvas.Top properties represent the distance between the top-left corner of the Canvas parent and the top-left corner of the control. By modifying the Left property in the Properties window, you act on the Canvas.Left property, and by modifying the Top property in the Properties window, you operate on the Canvas.Top property.

Use the StackPanel panel

The role of the StackPanel control is to position the child elements below each other or side by side depending on the Orientation property.

1. Create a new Application project. To do that, open Visual Studio 2012 and from the File menu select New Project. Choose Windows Store from the list of installed templates, and then choose Blank App (XAML) from the list of available projects.

2. Select version 4.5 as the .NET Framework version for your new project.

3. Name the new project StackPanel, and then choose a location on your file system and a solution name. When you’re finished, click OK.

4. Click the Toolbox tab that appears on the left of the form in the Design View window.

5. Expand the Common XAML Controls section.

6. Click the StackPanel control and drag it within the form.

7. Modify the dimensions and position of the StackPanel control until you get something that resembles the following graphic.

image with no caption

8. In the Toolbox Tab, select a Button control and drag it within the StackPanel.

9. Modify the Margin, Height, and Width properties as you like. For a better result to the procedure, set the Height property about one quarter of the StackPanel height (about 150 pixels).

10.Click the Button control in the Design View window.

11.Press Ctrl+C to copy the control. Press Ctrl+V. You will notice a new Button control placed right under the preceding button.

12.Press Ctrl+V two more times. You will notice two other Button controls placed according to the StackPanel behavior. You will find the result of these steps in the StackPanelVertical sample.

13.In the Design View window, select the StackPanel control by clicking inside the area defined by the control, but not on any of the buttons. Press Delete.

14.Click the Toolbox tab that appears on the left-hand side of the form in the Design View window.

15.Expand the All XAML Controls section.

16.Click the StackPanel control and drag it within the form.

17.Modify the dimensions and position of the StackPanel control until you get something similar to the previous graphic.

18.From the Properties window, set the Orientation property to Horizontal.

19.From the Toolbox tab, select a Button control and drag it within the preceding StackPanel.

20.Modify the Margin, Height, and Width properties as you like. For a better result to the procedure, set to Width property about one quarter of the StackPanel height (about 250 pixels).

21.Click the Button control in the Design View window and press Ctrl+C to copy the control.

22.Press Ctrl+V. You will notice a new Button control positioned next to the preceding button.

23.Press Ctrl+V two more times. You will notice two more Button controls being positioned according to the StackPanel behavior. You will find the result of these steps in the StackPanelHorizontal sample.

24.On the Debug menu, click Start Debugging.

Use the ScrollViewer panel

The role of the ScrollViewer control is to enable scrolling (both vertical and horizontal) in the case of overflow of the content (that is, when its content exceeds the size of the ScrollViewer control).

1. Create a new Application project. To do that, open Visual Studio 2012 and from the File menu select New Project. Choose Windows Store from the list of installed templates, and then choose Blank App (XAML) from the list of available projects.

2. Select version 4.5 as the .NET Framework version for your new project.

3. Name the new project ScrollViewer, and then choose a location on your file system and a solution name. When you’re finished, click OK.

4. Click the Toolbox tab that appears on the left-hand side of the form in the Design View window.

5. Expand the All XAML Controls section.

6. Click the StackPanel control and drag it within the form.

7. Modify the dimensions and position of the StackPanel control until you get something that resembles the following graphic.

image with no caption

8. From the Toolbox tab, select a Button control and drag it within the preceding StackPanel.

9. Modify the Margin, Height, and Width properties as you like. For a better result to the procedure, set the Height property to about 215 pixels.

10.Click the Button control in the Design View window and press Ctrl+C to copy the control.

11.Press Ctrl+V. You will notice a new Button control placed below the preceding button.

12.Press Ctrl+V two more times until you get something similar to the following graphic.

image with no caption

Do not worry if the third button is only partially visible and the fourth is completely invisible.

13.On the Debug menu, click Start Debugging.

14.You will notice that at runtime the third button is partially visible (but still clickable), whereas the fourth button is completely invisible and therefore not usable.

15.Return to Visual Studio 2012. On the Debug menu, click Stop Debugging.

16.Right-click the StackPanel control in the Design View window, and then select Group Into | ScrollViewer.

17.Click the StackPanel node in the XAML pane.

18.In the Properties window, expand the Layout property and click Set To Auto next to the Width property.

image with no caption

19.Click the Set To Auto button next to the Height property.

20.On the Debug menu, click Start Debugging.

21.Place the mouse over a button and scroll between the various Button controls.

NOTE

The controls of the platform have been designed to natively support different types of input; therefore it is possible to scroll using touch gestures, digital pen, mouse, and keyboard (in the latter case, using the arrow keys or the Page Up and Page Down keys).

22.Return to Visual Studio 2012 by pressing Alt+Tab. On the Debug menu, click Stop Debugging.

Use the Grid panel

The purpose of the Grid control is to place its child elements in rows and columns.

1. Create a new Application project. To do that, open Visual Studio 2012 and from the File menu, select New Project. Choose Windows Store from the list of installed templates, and then choose Blank App (XAML) from the list of available projects.

2. Select version 4.5 as the .NET Framework version for your new project.

3. Name the new project Grid, and then choose a location on your file system and a solution name. When you’re finished, click OK.

4. Click the Toolbox tab that appears on the left-hand side of the form in the Design View window, expand the Common XAML Control section, and click the Grid control and drag it on the form.

Modify the dimensions and position of the Grid control until you get something similar to the following graphic.

image with no caption

5. In the Design View window, place the mouse pointer within the area between the top margin of the Grid control and the dotted border positioned a few pixels above the Grid control. You will notice that the pointer has changed its shape into a column delimiter.

image with no caption

6. Place the mouse at about one-third of the length and click. You can see the Design View window at the end of the operation in the following screenshot.

image with no caption

As a result of this action, two columns have been created inside the Grid control. The first column has a width equal (in our case) to 82* and the second column to 181*. Do not worry if your numerical values are different. By observing the XAML View, you will find that the XAML code is similar to the following code:

<Grid HorizontalAlignment="Left" Height="620" Margin="156,80,0,0" VerticalAlignment="Top"

Width="1052">

<Grid.ColumnDefinitions>

<ColumnDefinition Width="82*"/>

<ColumnDefinition Width="181*"/>

</Grid.ColumnDefinitions>

</Grid>

The Grid control uses the ColumnDefinitions property to define the number of columns and their properties. In the Design View window, you can add more columns at your will.

7. Hover the mouse a few pixels below the triangle-shaped icon that represents the boundary of a column. You will see the pointer of the mouse assuming the shape of two arrows pointing, respectively, to the left and right. While holding the left mouse button, move the mouse left or right to resize the column. Release the left button to confirm the position.

8. Hover the mouse a few pixels below the triangle-shaped icon (as to resize a column), double-click to delete the column, and then delete all the additional columns until you get something resembling the previous screenshot.

9. In the Toolbox window, select a Button control and drag it into the second column of the Grid.

Take a look at the markup code of the Button control in the XAML View and notice the attached property Grid.Column=”1”; this property is used by the parent Grid control to position the button in the second column. In case you want to place the Button control in the first column, simply change the code to Grid.Column=”0”.

NOTE

For the platform, omitting the Grid.Column property is the same as writing Grid.Column=”0”.

10.In the Design View window, drag the Button control inside the first column.

11.Place your mouse over the label that represents the width of the column (in our case, this is the label that shows the number 82*) and you’ll notice a new drop-down list above the column.

image with no caption

The main role of this drop-down list is to allow you to edit the properties of a ColumnDefinition. The ColumnDefinition class defines column-specific properties, like Width, that apply to Grid controls.

12.In the drop-down list, select Pixel. The underlying label will show a value without the * character (in our case, the value is 328).

This operation resulted in the creation of a ColumnDefinition with a fixed width of, in our case, 328 pixels.

13.From the drop-down list, select Auto to set the column width to the width of its children controls automatically. In this scenario, the actual width of the column will be the sum of the width of the button and its margins.

14.From the drop-down list, select Star to return to the initial situation. Do not worry if the numerical values are different, just make sure that the ColumnDefinition elements have their Width property set to Star; that is, their value contains the * character.

The Star option allows us to create columns with proportional width; this ratio will be maintained even at runtime. This option is very useful if you want to create user interfaces capable of adapting to different client screen resolution.

In this procedure, you have created two columns with the value, in our case, of 82* and 181*. (In your case, the actual values might be different.) From the runtime perspective, it means that if the first column is 82 times a “logical unit,” the second column will be 181 times that same unit—thus maintaining an identical ratio.

15.In the XAML View, modify the Width property of the two ColumnDefinition elements as follows (the property to edit is highlighted in bold):

16.<Grid.ColumnDefinitions>

17. <ColumnDefinition Width="1*"/>

18. <ColumnDefinition Width="2*"/>

</Grid.ColumnDefinitions>

This way, you can be sure that the width of the second column will always be double the width of the first column.

19.In the Design View window, place the mouse pointer into the area between the left edge of the Grid control and the dotted line that is just a few pixels from the left of the Grid control. You will notice that the pointer changes its shape into a row delimiter.

image with no caption

Stop the mouse at around a quarter of the height and left-click. In the following graphic, you can see the Design View window at the end of the operation.

image with no caption

This operation led to the creation of two rows inside the Grid control, the first one with a width (in this example) of 1* and the second column with a width of 4*. If you take a look at the XAML View, you will notice that the XAML code of the Grid control is similar to the following code (the code produced by the last operation is highlighted in bold):

<Grid HorizontalAlignment="Left" Height="620" Margin="156,80,0,0" VerticalAlignment="Top"

Width="1054">

<Grid.RowDefinitions>

<RowDefinition/>

<RowDefinition Height="4*"/>

</Grid.RowDefinitions>

<Grid.ColumnDefinitions>

<ColumnDefinition Width="1*"/>

<ColumnDefinition Width="2*"/>

</Grid.ColumnDefinitions>

<Button Content="Button" HorizontalAlignment="Left" Height="84"

Margin="57,18.556,0,0" VerticalAlignment="Top" Width="217" Grid.Row="1"/>

</Grid>

The Grid control uses the RowDefinitions property to define the rows and their properties.

Notice that the first RowDefinition does not have any Height property defined. In that case, the platform assumes Height=”*” or Height=”1*”, which is the same.

NOTE

A ColumnDefinition with no Width property is the same as a ColumnDefinition with Width=”*” or, if you prefer, Width=”1*”.

If you take a look at the markup code of the Button control in the XAML View, you can see the attached property Grid.Row = “1”; this property is used by the parent Grid control to position the child control in the specified row. If you need to place the Button control in the first line, you should specify Grid.Row = “0”.

NOTE

From the platform perspective, omitting the Grid.Row property equates to Grid.Row=”0”.

20.In the Design View window, add as many rows as you like.

Position the mouse a few pixels to the right of the triangle-shaped icon that represents the demarcation of a row and you’ll see that the pointer of the mouse takes the shape of two arrows pointing upwards and downwards. Holding the left mouse button, drag the mouse up or down to resize the affected row. Release the left mouse button to confirm the position.

21.Place the mouse a few pixels to the right of the triangle-shaped icon (as you would do to resize the row), double-click to delete the row, and then delete all the additional rows until you obtain something that resembles the previous graphic.

22.Place your mouse over the label that represents the height of the first line (in our scenario, it’s the label with the value of 1*) and you’ll notice a new drop-down list next to the row. The main purpose of this drop-down list is to allow you to modify the Height property of aRowDefinition. Opening the drop-down list will reveal a view similar to the following graphic.

image with no caption

23.In the drop-down list, select Pixel, and the underlying label will show a value without the * character (for instance, the value could be 124).

This operation allows you to create a RowDefinition with a fixed width of 124 pixels.

24.From the drop-down list, select Auto to automatically set the row height; it will be the height of its child controls to determine the actual height of the RowDefinition. In this sample scenario, there aren’t any children controls yet, therefore it seems that the row has been deleted, so just look at the XAML View to ensure the presence of both rows. Press Ctrl+Z to undo the last operation.

25.In the drop-down list, select Star to step back to the initial situation. Do not worry if the numerical values are different, just make sure that the Height property of both RowDefinition elements is set to Star; that is, its value presents the * character.

The Star option allows creating rows with proportional height, and this ratio will be maintained at runtime as well. This option is extremely important to design user interfaces capable of adapting to different client screen resolutions.

In this procedure, you have created two rows with the values of 1* and 4*. At runtime, it means that if the height of the first row is one “logic unit” high, the second row is four times higher—thus preserving the same fixed ratio.

26.In the Toolbox window, select a Button control and drag it into the second column and second row of the Grid control.

27.Modify the Margin, Height, and Width properties as you like. The XAML code of the new Button control should look like the following code:

28.<Button Content="Button" HorizontalAlignment="Left" Height="84" Margin="241,198,0,0"

VerticalAlignment="Top" Width="217" Grid.Row="1" Grid.Column="1"/>

Notice that the two attached properties, Grid.Row and Grid.Column, will be used by the parent Grid control to position the control properly.

29.On the Debug menu, click Start Debugging.

Use the Border panel

The Border class is not derived from the Panel base class; it cannot contain a list of user interface controls but it can contain a single child element. The purpose of the Border control is to draw a frame around a single child control, and it is mostly used for creating an appealing graphic effect around elements like round corners.

1. Create a new Application project. To do that, open Visual Studio 2012 and, from the File menu, select New Project. Choose Windows Store from the list of installed templates, and then choose Blank App (XAML) from the list of available projects.

2. Select version 4.5 as the .NET Framework version for your new project.

3. Name the new project Border, and then choose a location on your file system and a solution name. When you’re finished, click OK.

4. Click the Toolbox tab that appears in the left-hand side of the form in the Design View window.

5. Click the Border control and drag it within the form.

6. Modify the dimensions and position of the Border control until you get something that resembles the following graphic.

image with no caption

7. In the Design View window, click the Border control.

8. In the Properties window, expand Brush, and then click BorderBrush | Solid Color Brush. The underlying palette will display a color picker.

image with no caption

9. Click and drag the mouse inside the color picker, halting on whatever color you like (a light color, such as white, will look better).

10.Once you have finished, the palette will show the preview of the selected color within the rectangle next to the BorderBrush property, the color code (in this example, #FFFFFFFF), and various shades of red, green, blue, and alpha (the alpha is the transparency of the color). If you choose white, the palette will look like the following graphic.

image with no caption

NOTE

A higher transparency number produces an opaque color, whereas a lower number produces a more transparent color (one where the background can show through).

11.In the Properties window, expand the Appearance property group and set the BorderThickness property by assigning the value 10 to Left and Right, 20 to the Top, and 40 to the Bottom.

12.In the Properties window, set the CornerRadius property to the following values: 20,20,40,40.

The CornerRadius property represents the radii of a border’s corners: the first value (20, in the preceding example) specifies the radius of the top-left corner; the second value (20) specifies the radius of the top-right corner; the third (40) specifies the radius of the bottom-right corner; and the fourth (40) specifies the radius of the bottom-left corner.

NOTE

If only a single value is specified, that measure is applied to all of the TopLeft, TopRight, BottomRight, and BottomLeft corners of the CornerRadius.

image with no caption

13.On the Debug menu, click Start Debugging. The application will look like the designer surface shown in the previous graphic.

Use the Margin property

The Margin property describes the distance between an element and its child or peers. The use of this property enables very fine control of an element’s rendering position.

1. Create a new Application project. To do that, open Visual Studio 2012 and from the File menu, select New Project. Choose Windows Store from the list of installed templates, and then choose Blank App (XAML) from the list of available projects.

2. Select version 4.5 as the .NET Framework version for your new project.

3. Name the new project Margin, and then choose a location on your file system and a solution name. When you’re finished, click OK.

4. Click the Toolbox tab that appears on the left-hand side of the form in the Design View window.

5. Expand the Common XAML Controls section.

6. Click the Button control and drag it within the form.

7. In the XAML View, set the Height property with a value of 200. Set the Width property with a value of 450. Set the Margin property with values of 300,200,0,0.

image with no caption

8. In the Properties window, expand the Layout property group and take a look at the Margin property—where the value 300 represents the left margin, the subsequent value 200 defines the top margin, and the other two values represent the right and bottom margin, respectively. A value of 0 means that the margins have not been defined.

9. In the Design View window, follow the dashed line that starts from the right side of the button to the right side of the parent Grid control to find an icon shaped like an anchor. Click the icon.

By doing this, you have set a fixed margin with a specific value (for example 616, in the current sample, but in your application the actual values might be different).

10.In the Properties window, expand the Layout property group and make sure that the Width property is set to Auto. If it is not, click Set To Auto next to the Width property.

Attributing a value of Auto to the Width property (or omitting that property from the XAML code) shifts the task of assigning a width to the control onto the Margin property. In other words, at runtime the Button control will expand and collapse in compliance with the “contract” imposed by the Margin property; that is, a left margin of 300 pixels and a right margin of 616 pixels.

11.In the Visual Studio 2012 toolbar, click the drop-down list by the Local Machine button to open the menu shown in the following image.

image with no caption

12.Select Simulator and then click the green play icon.

Visual Studio 2012 will start the Windows 8 Simulator and then will run the application within that virtual environment.

13.In the simulator, click Change Resolution (positioned in the right toolbar of simulator) and select the first entry “10.6 1024 × 768.”

image with no caption

Notice that the button width varies according to the screen resolution.

14.Try other resolutions and notice the changes in the button width.

15.Return to Visual Studio 2012. On the Debug menu, click Stop Debugging.

16.In the Design view, follow the dotted line running from the underside of the button to the lower edge of the parent Grid control and you will find an icon with the shape of an anchor. Click that icon.

By doing this, you have set a fixed bottom margin with a specific value, which is 368 in the current example—but in your environment it might be different.

17.Drag the Button control towards the bottom-right margin of the parent Grid control.

Notice how the Margin property varies while you are dragging the control.

18.Click the anchor-shaped icon that represents the top margin.

Notice how the solid line changes its shape into a dashed line—this means that the margin value has been set to zero.

19.Click the anchor-shaped icon that represents the left margin.

Notice how the solid line changes its shape into a dashed line—this means that the margin value has been set to zero.

20.Set the Margin property through the XAML View to the following values: 0,0,80,80.

21.Make sure that the Width property of the Button control is set to any value other than zero (for example, 450).

22.On the Debug menu, click Start Debugging.

23.In the simulator, click Change Resolution and select whatever resolution you prefer.

24.Try other resolutions and observe the button: its dimensions, as well as its right and bottom margins, remain constant.

25.Return to Visual Studio 2012. On the Debug menu, click Stop Debugging.

Customize the appearance of controls

In the previous examples, you have set the various properties control by control. However, leveraging the features of the XAML platform, it is possible to centralize the layout definition of the various controls to improve the maintainability of the solution and create a consistent appearance for the product.

Another feature of the XAML styling model is the separation between presentation and logic. It means that designers can focus on the appearance of the application, whereas developers can take care of the application logic.

You will start this section by reusing a style that is already included in the Visual Studio 2012 project. Then you will customize that style. Lastly, you will create a new style from scratch and use templates to redefine the structure of a control.

Use a predefined style

A Style element is a container of property values. In this procedure, you will use a Style element that is already included in the Visual Studio 2012 project template.

1. Create a new Application project. To do that, open Visual Studio 2012 and, from the File menu, select New Project. Choose Windows Store from the list of installed templates, and then choose Blank App (XAML) from the list of available projects.

2. Select version 4.5 as the .NET Framework version for your new project.

3. Name the new project UsingStyles, and then choose a location on your file system and a solution name. When you’re finished, click OK.

4. Click the Toolbox tab that appears on the left-hand side of the form in the Design View window.

5. Expand the Common XAML Controls section.

6. Click the TextBlock control and drag it within the form.

7. In the XAML View, set the Margin property to 200,100,0,0.

8. In the Design View, select the TextBlock control and open the contextual menu by right-clicking.

image with no caption

9. Select Edit Style | Apply Resource. Then select PageHeaderTextStyle in the inner menu.

In the XAML View, take a look to the XAML code of the TextBlock control—it should look like the following code:

<TextBlock HorizontalAlignment="Left" Margin="200,100,0,0" TextWrapping="Wrap"

Text="TextBlock" VerticalAlignment="Top"

Style="{StaticResource PageHeaderTextStyle}"/>

The previous operation has set the Style property with a reference to a shared resource called PageHeaderTextStyle.

10.In the Solution Explorer window, expand the Common directory and double-click the StandardStyles.xaml file.

11.Press Ctrl+F and, in the textbox, type PageHeader. Visual Studio 2012 will shift the focus to the definition of the style named PageHeaderTextStyle. The markup code should look like the following:

12.<Style x:Key="PageHeaderTextStyle" TargetType="TextBlock"

13. BasedOn="{StaticResource HeaderTextStyle}">

14. <Setter Property="TextWrapping" Value="NoWrap"/>

15. <Setter Property="VerticalAlignment" Value="Bottom"/>

16. <Setter Property="Margin" Value="0,0,30,40"/>

</Style>

As you can see, a style is just a container of property settings—as the properties TextWrapping, VerticalAlignment, and Margin illustrate.

Starting from the first line of code for the style, you can find its name, expressed by the x:Key attribute, the kind of controls that can use it (TextBlock, in this case), and finally the BasedOn attribute, which indicates from which style it derives (it means that the PageHeaderTextStyle style will inherit all the settings of the base style, plus its own personal settings).

Customize a predefined style

A Style element is a container of property values. In this procedure, you will customize a Style element that is already included in the Visual Studio 2012 project template.

1. Create a new Application project. To do that, open Visual Studio 2012 and, from the File menu, select New Project. Choose Windows Store from the list of installed templates, and then choose Blank App (XAML) from the list of available projects.

2. Select version 4.5 as the .NET Framework version for your new project.

3. Name the new project CustomStyles, and then choose a location on your file system and a solution name. When you’re finished, click OK.

4. Click the Toolbox tab that appears on the left-hand side of the form in the Design View window.

5. Expand the Common XAML Controls section.

6. Click the TextBlock control and drag it within the form.

7. In the XAML View, set the Margin property to 200,100,0,0.

8. In the Design View, click the TextBlock control and right-click to open the contextual menu. From the menu, select Edit Style | Apply Resource | PageHeaderTextStyle.

9. In the Design View, click the TextBlock control and right-click to open the contextual menu. From that menu, select Edit Style | Edit Current.

Replace the following PageHeaderTextStyle style definition:

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

BasedOn="{StaticResource HeaderTextStyle}">

<Setter Property="TextWrapping" Value="NoWrap"/>

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

<Setter Property="Margin" Value="0,0,30,40"/>

</Style>

with this code:

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

BasedOn="{StaticResource HeaderTextStyle}">

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

<Setter Property="TextWrapping" Value="NoWrap"/>

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

<Setter Property="Margin" Value="0,0,30,40"/>

</Style>

The new line of code that will customize the control’s foreground color is highlighted in bold.

10.In Solution Explorer, double-click MainPage.xaml.

Notice how the foreground color of the TextBlock control is now red.

11.Click the Toolbox tab.

12.Expand the Common XAML Controls section.

13.Click the TextBlock control and drag it within the form, then move it under the previously added control.

14.Click the new TextBlock control and right-click to open the contextual menu. In the menu, select Edit Style | Apply Resource | PageHeaderTextStyle.

Observe the new control again: the foreground color is red, meaning that it uses the custom definition of a predefined style.

15.On the Debug menu, click Start Debugging. The result is shown in the following graphic.

image with no caption

Customize the copy of a predefined style

A Style element is a container of property values. In this procedure, you will customize a copy of a Style element that is already included in the Visual Studio 2012 project template.

1. Create a new Application project. To do that, open Visual Studio 2012 and from the File menu, select New Project. Choose Windows Store from the list of installed templates, and then choose Blank App (XAML) from the list of available projects.

2. Select version 4.5 as the .NET Framework version for your new project.

3. Name the new project CopyStyles, and then choose a location on your file system and a solution name. When you’re finished, click OK.

4. Click the Toolbox tab that appears on the left-hand side of the form in the Design View window.

5. Expand the Common XAML Controls section.

6. Click the TextBlock control and drag it within the form.

7. In the XAML View, set the Margin property to 200,100,0,0.

8. In the Design View, click the TextBlock control and right-click to open the contextual menu. In the menu, select Edit Style | Apply Resource | PageHeaderTextStyle.

9. In the Design View, click the TextBlock control and right-click to open the contextual menu. In that menu, select Edit Style | Edit A Copy to open the Create Style Resource modal window.

10.In the Name property field, type MyPageHeaderTextStyle and make sure that This Document is selected. Click OK.

image with no caption

11.Replace the PageHeaderTextStyle style definition that follows:

12.<Style x:Key="MyPageHeaderTextStyle" TargetType="TextBlock"

13. BasedOn="{StaticResource HeaderTextStyle}">

14. <Setter Property="TextWrapping" Value="NoWrap"/>

15. <Setter Property="VerticalAlignment" Value="Bottom"/>

16. <Setter Property="Margin" Value="0,0,30,40"/>

</Style>

with this code:

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

BasedOn="{StaticResource HeaderTextStyle}">

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

<Setter Property="TextWrapping" Value="NoWrap"/>

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

<Setter Property="Margin" Value="0,0,30,40"/>

</Style>

The new line of code that will customize the control’s foreground color is highlighted in bold.

Notice how the foreground color of the TextBlock control is now red.

17.Click the Document Outline tab.

18.Click the Return Scope To [Page] button positioned right by the style name (MyPageHeaderTextStyle). The following graphic shows the Document Outline tab.

image with no caption

This operation is quite important because it allows leaving the style editing mode and going back to the design layout mode.

19.Click the Toolbox tab.

20.Expand the Common XAML Controls section.

21.Click the TextBlock control, drag it within the form, and then move it below the previously added control.

22.Click the TextBlock control you just added, and then right-click to open the contextual menu. Select Edit Style | Apply Resource | MyPageHeaderTextStyle. Your new style has been created by starting from a predefined one.

23.On the Debug menu, click Start Debugging. The result will look similar to the final graphic in the previous procedure.

Create a new style

A Style element is a container of property values. In this procedure, you will create a new style from scratch.

1. Create a new Application project. To do that, open Visual Studio 2012 and from the File menu, select New Project. Choose Windows Store from the list of installed templates, and then choose Blank App (XAML) from the list of available projects.

2. Select version 4.5 as the .NET Framework version for your new project.

3. Name the new project NewStyles, and then choose a location on your file system and a solution name. When you’re finished, click OK.

4. Click the Toolbox tab that appears on the left-hand side of the form in the Design View window.

5. Expand the Common XAML Controls section.

6. Click the TextBlock control and drag it within the form.

7. In the XAML View, set the Margin property to 200,100,0,0.

8. In the Design View, click the TextBlock control, and right-click to open the contextual menu. Select Edit Style | Create Empty to open the Create Style Resource modal window.

9. In the Name property field, type MyTextBlockStyle and make sure that This Document is selected. Click OK.

10.In the Properties window, expand the Brush property group, click the Foreground property, and, in the color picker, choose whatever color you like.

11.Take a look at the XAML View, every operation executed in the Properties window is being recorded as a Setter of the style object.

NOTE

It is possible to set the Setters of a Style object through the XAML View by directly typing the corresponding XAML code, or by using the visual tools exposed by the Properties window in Visual Studio 2012.

12.In the Properties window, expand the Text property and set the FontSize property to 48px. This property is located next to the drop-down list box containing the name of the font.

13.Expand Show Advanced Properties in the Text section.

image with no caption

14.Set the FontWeight property to Light.

15.Click the Document Outline tab.

16.Click Return Scope To [Page], located at the left by the style name (MyTextBlockStyle).

17.Click the Toolbox tab.

18.Expand the Common XAML Controls section.

19.Click the TextBlock control and drag it within the form, and then move it below the previously added control.

20.Click the TextBlock control you just added and right-click to open the contextual menu. Select Edit Style | Apply Resource and then select the new MyTextBlockStyle style that you just created.

21.On the Debug menu, click Start Debugging. The result will look similar to the last graphic of the previous procedure.

Create a new template

The ControlTemplate of a control defines the appearance of the control. In this procedure, you will create a new template from scratch.

1. Create a new Application project. To do that, open Visual Studio 2012 and, from the File menu, select New Project. Choose Windows Store from the list of installed templates, and then choose Blank App (XAML) from the list of available projects.

2. Select version 4.5 as the .NET Framework version for your new project.

Name the new project NewTemplate, and then choose a location on your file system and a solution name. When you’re finished, click OK.

3. Click the Toolbox tab that appears on the left-hand side of the form in the Design View window, expand the Common XAML Controls section, click the Button control, and drag it within the form.

4. In the Properties window, expand the Layout property group and set the Width property to 400 and the Height property to 400.

5. In the Design View, drag the Button control to roughly the center of the page, right-click the button to open the contextual menu, and select Edit Template | Create Empty to open the Create ControlTemplate Resource modal window.

6. In the Name property field, type MyButtonControlTemplate and make sure that This Document is selected. Click OK.

Visual Studio 2012 will enter the editing mode of the ControlTemplate of the button.

A ControlTemplate is a fragment of XAML code capable of representing the structure of a user interface control.

7. Click the Document Outline tab.

NOTE

If you want to keep the Document Outline always visible, click Auto Hide, positioned to the right of the title bar.

Notice the default structure of a ControlTemplate—Visual Studio 2012 has inserted a Grid control as the root element of the template.

8. Click the Toolbox tab, expand the All XAML Control section, click the Ellipse control, and drag it inside the Grid control.

9. In the Design View, click the Ellipse control and right-click to open the contextual menu. Select Reset Layout | All. The Ellipse control will fill the whole parent element.

10.In the Properties window, expand the Brush property group, click the Fill property, and then click the Local button positioned to the right of the rectangle showing the preview.

image with no caption

11.In the contextual menu of the Local button of the Fill property, select Reset.

Make sure that the background of the Ellipse control is set to transparent.

12.In the Properties window, click Stroke and in the color picker, choose white (#FFFFFFFF).

13.Expand the Appearance property and set the StrokeThickness property to 10.

NOTE

The StrokeThickness property represents the width of the object outline.

14.Click the Toolbox tab, expand the All XAML Controls section, and click the TextBlock control and drag it within the form, inside the Grid control.

15.In the Properties window, expand the Layout property group.

16.In the contextual menu of the Local button of the Margin property, select Reset.

17.In the Properties window, set both HorizontalAlignment and VerticalAlignment to Center.

Observe how the TextBlock control is being centered within the parent Grid control.

18.Expand the Miscellaneous property group, click the Default button next to the Style property and from the contextual menu, select Local Resources | PageHeaderTextStyle.

19.Expand the Layout property group (if not already expanded) and set both the right and bottom margins to 0.

20.Expand the Common property group, click the Local button next to the Text property and from the contextual menu, select Template Binding | Content.

With this operation, you have bound the Content property of the button, which is going to use this template with the Text property of the TextBlock control.

21.Click the Document Outline tab and click Return Scope to [Page], which is located next to the name of the template (MyButtonControlTemplate).

22.In the Design View, click the Button control.

In the Properties window, expand the Common property group and, in the Content property, type Save.

23.Click the Toolbox tab, expand the Common XAML Controls section, and click the Button control and drag it within the form, side by side with the previously added control.

In the Properties window, expand the Layout property group and set both the Width and the Height properties to 400.

Expand the Common property group and, in the Content property, type Cancel.

24.In the Design View, click the Button control you just added and right-click to open the contextual menu. Select Edit Template | Apply Resource, and then choose the new MyButtonControlTemplate template that you just created.

image with no caption

25.On the Debug menu, click Start Debugging. The application will look similar to the designer surface shown in the previous graphic.

If the right side of the Cancel button is cut off, return to Visual Studio 2012 and move the two buttons to the left side of the screen.

Use a predefined template

The ControlTemplate of a control defines the appearance of the control. In this procedure, you will reuse a ControlTemplate element included in the Visual Studio 2012 project template.

1. Create a new Application project. To do that, open Visual Studio 2012 and, from the File menu, select New Project. Choose Windows Store from the list of installed templates, and then choose Blank App (XAML) from the list of available projects.

2. Select version 4.5 as the .NET Framework version for your new project.

3. Name the new project UsingTemplate, and then choose a location on your file system and a solution name. When you’re finished, click OK.

4. Click the Toolbox tab that appears on the left-hand side of the form in the Design View window.

5. Expand the Common XAML Controls section.

6. Click the Button control and drag it within the form.

7. In the Properties window, expand the Layout property group, and set both the Width and the Height properties to 400.

8. In the Design View, drag the Button control to roughly the center of the page.

9. In the Design View, click the Button control and right-click to open the contextual menu. Select Edit Template | Apply Resource | TextButtonStyle.

This ControlTemplate will make the button very similar to a TextBlock visually without affecting its behavior. The ability to manage the common events of the Button class, such as the Click event, will not be affected.

Customize a predefined template

The ControlTemplate of a control defines the appearance of the control. In this procedure, you will customize a ControlTemplate element included in the Visual Studio 2012 project template.

1. Create a new Application project. To do that, open Visual Studio 2012 and, from the File menu, select New Project. Choose Windows Store from the list of installed templates, and then choose Blank App (XAML) from the list of available projects.

2. Select version 4.5 as the .NET Framework version for your new project.

3. Name the new project CustomTemplate, and then choose a location on your file system and a solution name. When you’re finished, click OK.

4. Click the Toolbox tab that appears on the left-hand side of the form in the Design View window.

5. Expand the Common XAML Controls section.

6. Click the Button control and drag it within the form.

7. In the Properties window, expand the Layout property group, and set both the Width and the Height properties to 400.

8. In the Design View, drag the Button control to roughly the center of the page.

9. In the Design View, click the Button control and right-click to open the contextual menu Select Edit Template | Apply Resource | TextButtonStyle.

10.In the Design View, click the Button control again and right-click to open the contextual menu. Select Edit Template | Edit Current.

11.Click the Document Outline tab.

12.In the Document Outline tab, expand the Template node (if not already expanded), expand the Grid node, and finally, click the Text node.

Thanks to this operation, you have selected the TextBlock control inside the template.

NOTE

You can select a control of the ControlTemplate by clicking it in the Design View.

13.In the Properties window, expand the Brush property group and click the Default button next to the Foreground property. Select Template Binding | Foreground.

14.Expand the Layout property group, click the Default button next to the Margin property, select Template Binding, and then click Padding.

NOTE

The Padding property represents the distance between the child elements of a control.

15.In the Document Outline tab, click Return Scope To [Page] next to the template name (TextButtonStyle).

16.In the Design View, click the Button control.

17.In the Properties window, expand the Brush property group, and choose whatever color you like for the Foreground property.

18.Expand the Text property and set the FontSize property to 72px.

19.Click Show Advanced Properties and set the FontWeight property to Light.

20.Expand the Layout property group, click Show Advanced Properties, and set both the left and top padding to 80.

Summary

In this chapter, you have learned how to use Visual Studio 2012 to create an application by using visual tools, how to define the layout of a Windows 8 application through the Canvas, Grid, StackPanel, and ScrollViewer panels, and finally, how to customize the appearance of a visual control through the Style and ControlTemplate objects.

Quick reference

To

Do this

Add a Grid control to the layout

Click the Toolbox tab, expand the All XAML Controls, click the Grid control, and drag it within the form.

Add a StackPanel control to the layout

Click the Toolbox tab, expand the All XAML Controls, click the StackPanel control, and drag it within the form.

Add a Canvas control to the layout

Click the Toolbox tab, expand the All XAML Controls, click the Canvas control, and drag it within the form.

Use a predefined style

In the Design View, click the desired control, right-click and select Edit Style | Apply Resource, and select the style.

Use a predefined template

In the Design View, click the desired control, right-click and select Edit Template | Apply Resource, and select the template.