This chapter covers the basic things that can be done using the XAML language and the presentation layer that it depends on:
XAML introduction
Basic WP8 controls
Windows Phone Toolkit
Working with data
XAML (Extensible Application Markup Language) is an important part of the .NET platform that allows us to build rich and beautiful applications. There are a few ways to build a Windows Phone application; we decided to follow the XAML with C# path because this technology, despite its richness, is very comfortable to use and relatively easy to handle. The multiplicity of controls and features that we get out of the box with Visual Studio is enough to build and publish Windows Phone 8 applications.
As XAML is grammar based on XML, anyone who has a web developer's background will find it intuitive. The main goal of using this markup language is to simplify the cooperation between graphic designer and developers, but it doesn't mean that you need to have designer skills to create an XAML application and vice versa; if a graphic designer wants to help with the application design, it is not necessary to know C# (but it can be helpful). If you are still afraid of XAML code and want to try it yourself, take help of a graphic designer and almost do not touch the GUI code. You should try the Designer tool that is a part of Visual Studio or the fancier Expression Blend. Graphic designers prefer to use Blend because they can create a whole user interface, animations, and so on without writing XAML code. But we will write the code because we are developers!
The XAML specification defines the rules of mapping the .NET classes to XAML objects; for example, the following is how we define a button in XAML:
<Button Name="BtnMyButton" Click="BtnMyButton_OnClick" Content="Click me!"> </Button>
It means the same as:
System.Windows.Controls.Buttonbutton = new System.Windows.Controls.Button(); button.Name = "BtnMyButton"; button.Content = "Click Me!"; button.Click += BtnMyButton_OnClick;
But we will never do that! Defining controls, containers, and so on in C# code is against patterns and good practices, and causes my soul to suffer.
XAML objects can be grouped into 6 groups as follows:
Navigation
Containers
List controls
Common controls
User controls
Third-party controls
Navigation controls ensure that the Windows Phone application works in a similar way to page navigation in a web browser.
PhoneApplicationFrame
is a top-level container and only one can be defined for the entire application. PhoneApplicationFrame
can contain pages and implements navigation by calling the Navigate
method or setting the Content
property. I suggest using the Navigate
method because it adds entry to the BackStack
enumerable (the list of entries in the navigation history). In this way, it allows the back button to be automatically handled by getting the history elements from the history stack.
Containers are very important in application design. It allows us to organize content the way we want to.
Canvas
is one of the Panel
containers and can contain child elements. Child objects within Canvas
have their position defined by x, y (Canvas.Left
, Canvas.Top
) properties, which specifies the distance in pixels from the left (x) to the top(y) corner of Canvas
.
Border
is a container that delivers border or/and background around other controls and can have only one child.
Grid
is a Panel
type container. Within Grid
, we can create grid columns and rows, and then position objects by the Row
and Column
property on the control. Distribution of spaces is really simple using star sizing (means stretching to place that is split equally) or Auto value. Grid
contains elements that are drawn in the order that they are defined in the container . Using the ZIndex
property on the elements of Grid
, we can define which element will appear at the front and at the back.
Panorama
is a long horizontal canvas that contains PanoramaItem
. It is commonly used in Windows Phone. Panorama
is an ideal place to put long horizontal content into as it provides a better user experience. The best thing is, we don't need to handle any gestures (swipe, flick) because it does these automatically.
Pivot
is another container that can be used instead of the Panorama
control. It contains PivotItems
that provide a quick way to manage pages or other views, just as Panorama
has gesture handling implemented by default.
Most applications display some data, often lists of items. When we need to show a list, we can use one of the list controls.
Mobile applications, though they are completely different, have many common elements. There are a number of controls that are available for developers in the Visual Studio toolbox.
ApplicationBar
is a control that contains icon buttons. The bar is placed at the bottom of the application page and can contain buttons that launch default actions on the page, such as add, delete, save, and edit. The application bar can be shown in the following three states/sizes:
Mini size: Where only three dots are visible and the user can slide up the bar
Default size: Where buttons and ellipsis are visible
Full size: Where buttons, ellipsis, and labels are visible
This control is used in many places in Windows Phone 8 and is really intuitive.
Button
is one of the most frequently used controls. When the user touches the Button
control, it causes the execution of the Click
event method handler that is assigned to it. What is interesting is that we can set when the event will be fired by changing ClickMode
. For example, if we set ClickMode
to Press
, the event handler will be executed when the user taps on it. A release setting (a default setting) action will be launched when the user releases the button.
CheckBox
represents a Boolean value, a choice between two opposite states, and is often used in a group.
HyperlinkButton
works and looks like any web hyperlink. Tapping on the hyperlink opens mobile IE or a web view in our application.
Using the Image
control, we can show standard web format images in our application. Images respond to typical gestures in WP, such as tap, double-tap, pan, flick, and pinch-and-stretch.
A good practice is to display a picture that has a similar resolution to our image control.
MediaElement
has no interface of its own; that is, it just shows media (audio/video) content. It can be customized by its properties to display the video on a full-screen, and if there is an audio playing, the background sound can be muted. What is important is that only one MediaElement
control can be used at a time.
MultiScaleImage
in used in Deep Zoom technology. This control allows the user to open a multiresolution collection of pictures or a single picture. Methods for panning and zooming are not implemented by default but should be utilized.
PasswordBox
is used to input passwords (for logging in or registering purposes). It is displayed like TextBox
, but the difference is that the entered letters show only for the moment and are normalized to bullets. The number of displayed bullets is not equal to the number of letters in the Text
property.
Popup
displays content that overlays current content. Using the IsOpen
property, this control shows or hides the pop up. We can use the MessageBox
control, which is a less-flexible component.
MessageBox
is a modal dialog that shows at the top of the application page. MessageBox
can be displayed by calling the static Show
method on the MessageBox
class. Because of that, such controls should not be used since they create the dependency of the user interface in the code.
RadioButton
like CheckBox
represents a Boolean value but can be grouped with that, which provides mutual exclusivity.
RichTextBox
represents a rich text-editing control that allows hyperlinks, images, formatted texts, and HTML elements.
Slider
displays a range of values along the track that the user can select from. The selected position is represented by the Value
property.
TextBlock
is one of the most common controls in Windows Phone 8. It displays read-only text, which can be set by the Text
property.
ToggleButton
is very similar to CheckBox
and RadioButton
and is used to switch states. It is most commonly used in the Settings page.
WebBrowser
displays HTML in our application. This control is based on the Internet Explorer 10 engine. Using WebBrowser
, we are able to display the web content by using the Source
property. It is good to remember that the control has disabled scripts by default; if we want to use some JavaScript, we have to switch the IsScriptEnabled
flag on it.
User controls provide encapsulation of some functionality. Imagine a situation where you created some form and would like to use it on another pageâdon't even think about copy and paste! The best solution for this will be to create a user control.
User controls are easy to createâjust add the new item to the solution, select the WP user control, and put controls into it.
<UserControl x:Class="MyCustomControls.UsrControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <StackPanel HorizontalAlignment="Center"> <TextBlock Text="Hello from User Control!"></TextBlock> </StackPanel> </UserControl>
Now imagine you can put a user control into ListBox
or other list control. For sure, using user controls will save your time, and the code will look clearer.
Windows Phone Toolkit is based on the Microsoft Public License, so you can use it on the terms of this license. The toolkit library provides many controls that are way better than the common ones and there are some new one with nice features. For sure, using this toolkit will provide a rich user experience to our application, making users feel better about using it longer. The following is a list of some of the most popular controls used in WP Toolkit:
AutoCompleteBox
ContextMenu
CustomMessageBox
DatePicker
HubTile
MapExtensions
ExpanderView
LongListMultiSelector
- List layoutLongListMultiSelector
- Grid layoutListPicker
ToggleSwitch
This is not the end! Windows Phone Toolkit also contains a test framework that will be used later when the Model-View-ViewModel (MVVM) pattern will be described. Why should unit testing be important for developers? Because it is not only a way to test the application; it is a way to create softwareâwriting a code. Agile development practices require us to write and execute unit tests.
Two ways to get Windows Phone Toolkit are as follows:
Downloading from CodePlex by browsing to: http://phone.codeplex.com/
Executing the Package Manager Console command
PM> Install-Package WPtoolkit
We now know about many controls and containers; now it is time to populate them with some data. As always, there are multiple ways to put dataâ textbox, button, listbox, and so onâbut, following the modern best practices, I will go with data binding. Data binding defines the way the data is linked to the properties of Model
and interacts with the user. Using this mechanism, data is separated from the code that manages data. There are a few things that are important to know when starting to work with the data in Windows Phone. We will be dealing with some of them in the following section.
Imagine you have just created a WP8 solution, dragged-and-dropped the TextBlock
control into the page, and now you need to tell the textbox what it has to display. As always, there are multiple ways to do that. First is the binding expression that is used in XAML. Binding expressions should be defined between curly braces "{" and "}".
To visualize this method, let's define the class Customer
, which will be used further in this chapter, and call it Model
.
public class Customer { public string Name { get; set; } public string Lastname { get; set; } public string Email { get; set; } public DateTime DateOfBirth { get; set; } public bool IsMarried { get; set; } public Country Location { get; set; } }
Consider a situation where you want to bind the Customer
class property to the TextBlock
control that you have already defined. Using simple binding can be done in a few ways, as seen in the following code:
<StackPanel> <TextBlock Text="{Binding Path=Lastname}"/> <TextBlock Text="{Binding Name}"/> <TextBlock Text="{Binding Country.IsoCode}"/> </StackPanel>
The preceding example shows how to link particular properties from Model
(the Customer
class) with the Text
property of the TextBlock
control. The first and second code lines have the same meaning; the path keyword can be omitted in simple expressions. The third example is a bit more sophisticated and binds the IsoCode
property from an embedded object in the Customer
model.
Most controls have the DataContext
property. DataContext
is accessible from the code and setting it will tell the XAML object which model it should use. Binding expressions that we have defined previously while resolving the value will look for the data context from leaf to root, meaning from TextBlock
to StackPanel
and next in any parent container.
var customer = new Customer() { Name = "John", Lastname = "Smith", DateOfBirth = new DateTime(1988, 1, 3) }; StckContainer.DataContext = customer;
Now, the model is linked to the container but it can be any other parent container or UserControl
.
During development, we will often face a situation where one element will depend on another element's property.
<StackPanel Name="StckContainer"> <Slider x:Name="SliderSize" Minimum="10" Maximum="72" Value="12" ></Slider> <TextBlock Text="{Binding Path=Lastname}" FontSize="{Binding Value, ElementName=SliderSize}"/> </StackPanel>
The preceding example shows a Slider
control that manages the font size of TextBlock
. Using this type of binding, we have to initialize the ElementName
property with a name and path to attribute of dependent control. This is a very simple demonstration; such bindings are used in much more advanced situations such as hiding UI elements or changing the control's content.
There are three binding modes that can be defined in the binding expressionas follows:
OneTime
: This is the default binding mode. It populates a property with data when loading for the first time.OneWay
: This should be used for read-only controls. When the model changes, the control (UI) property will be updated.TwoWay
: This should be used within the editable form, where a user has to input some data. For example, theName
andLastname
textboxes. It updates the model and UI automatically.
The OneWay
and TwoWay
modes need the INotifyPropertyChanged
interface to be implemented in a model that is linked to the control.
Why do we need the INotifyPropertyChanged
interface? It implements events in our model class that will update the UI when the model changes (for example, when the Name
property in the Customer
class changes). This behavior is really useful when the application updates data in the background; changes will be directly seen in the UI.
More about the INotifyPropertyChanged
interface implementation and binding to property will be covered in Chapter 3, Building a Windows Phone 8 Application using MVVM.
Sometimes, developers need to display show data differently from how it is stored in a model or database. If you ever experience this, remember value converters. IValueConverter
is an interface that implements the following two methods:
A good example of converting the data is the DateTime
converter. To define the converter, we have to remember two steps. First, create a class that implements IValueConverter
, and then use it in XAML in the control resource. Out of experience, I suggest creating such converters in one location or library to keep our code clear and reuse it them in many projects.
Another very important topic is binding a list. It is hard to even imagine an application without lists. Lists or collections, which are pretty much the same, can be linked to list control using a binding mechanism. It is very easy to implement in a markup definition.
<ListBox Name="ListCustomers" ItemsSource="{Binding}" DisplayMemberPath="Name"> </ListBox>
The trickiest part goes in code. Remember when we were talking about INotifyPropertyChanged
? We can create a list of any objects, bind it to the list, and the list will automatically handle updating of the UI. ObservableCollection
is a generic collection that provides notification when the items get removed, or added, or when refreshed. Look at the following code and see how simply I did that!
ObservableCollection<Customer> customers = new ObservableCollection<Customer>(); ListCustomers.DataContext = customers; customers.Add(customer);
In this example, the collection was created, linked to the ListBox
control, and one object was added to the collection in code. Because of the features of the observable collection, the UI gets updated because of implicit binding.
In this chapter we were talking about XAML controls, updated UI, and took the first few steps in working with data presentation. Readers should now know which and how controls can be used, what data binding is, and know about value converters.
The next chapter will be less technical; there will be more about planning, inventing, and designing our application.