In this chapter, we will cover the following recipes:
Setting up the IDE
Arranging windows
Creating a new project
Running the application
Adding a new page
Placing a control
Handling events
Navigating between pages
Passing data between pages
Handling the back button
Changing a default page
Modifying the back stack
Utilizing additional features of the emulator
Breakpoints-based debugging
Step-by-step debugging
Executing code while debugging
Logging information while debugging
Monitoring the CPU and memory usage
Application development is certainly an exciting task that allows you to create amazing solutions that may be used by people all over the world! What is more, with the usage of the Windows 10 platform, you can develop Universal Windows Platform (UWP) applications that run on various devices, including smartphones, tablets, and desktops. The availability of great tools and a lot of interesting resources make such a task significantly easier. Additionally, they shorten the time required for preparing the product. So, why not try developing another great solution that could be known and used in various regions of the world?
However, before developing amazing applications and sharing them with others, you need to perform a set of necessary steps, such as setting up a suitable Integrated Development Environment (IDE), creating a project, or adding pages to your application. Then, you need to design a User Interface (UI) as well as handle suitable navigation within the application. You also need to write supporting code in a programming language as well as test the newly created application in an emulator and a real device.
Unfortunately, sometimes not everything works exactly as you plan. Therefore, it is important to learn how to debug your solution and find the source of the problem as well as measure performance to ensure that the application will work smoothly on various devices.
In the case of this book, we will use Extensible Application Markup Language (XAML) for UI definition as well as the C# programming language to specify the interaction with the UI and to prepare business logic.
If you are already aware of the previously mentioned topics, you could skip this chapter. Otherwise, it is strongly recommended that you read it thoroughly because the information will be used in the remaining part of this book as well. Let's start!
Tip
You can find more information about various topics presented in the book at https://developer.microsoft.com/en-us/windows/apps/develop. This website contains a lot of interesting resources regarding developing UWP applications for Windows 10, such as about:
The XAML platform (https://msdn.microsoft.com/windows/uwp/xaml-platform/index)
Controls (https://msdn.microsoft.com/windows/uwp/controls-and-patterns/index)
Data binding (https://msdn.microsoft.com/windows/uwp/data-binding/index)
Files and folders (https://msdn.microsoft.com/windows/uwp/files/index)
Sensors (https://msdn.microsoft.com/windows/uwp/devices-sensors/sensors)
Graphics and animation (https://msdn.microsoft.com/windows/uwp/graphics/index)
Maps and location (https://msdn.microsoft.com/windows/uwp/maps-and-location/index)
Audio, video, and camera (https://msdn.microsoft.com/windows/uwp/audio-video-camera/index)
Downloading, launching, and configuring an IDE is the first step that you should perform to start developing applications for smartphones, tablets, and desktops running on the Windows 10 operating system. With the usage of a convenient environment, a developer can easily design UI, write code, debug the application, as well as deploy it on an emulator or a real device.
In this book, we will use Microsoft Visual Studio Community 2015.
Note
Of course, Microsoft Visual Studio Community 2015 is not the only IDE that one can use to develop solutions for Windows 10. There are also other versions of Microsoft Visual Studio that you could use, such as Professional and Enterprise. You can take a look at the comparison between the various versions of Microsoft Visual Studio 2015 at: https://www.visualstudio.com/en-us/vs-2015-product-editions .
To step through this recipe, you need a PC that meets the requirements that are necessary to run Microsoft Visual Studio Community 2015.
To install the IDE, you need to perform the following steps:
Download the installation file of Microsoft Visual Studio Community 2015 from: https://www.visualstudio.com/en-us/products/visual-studio-community-vs .
Open the downloaded file and wait until the installer is started.
Choose the Custom installation type, as presented in the following image (on the left). Then, click on the Next button.
Check all the options within the Universal Windows App Development Tools group in the Select features part, as shown in the image (on the right). Then, click on Next.
Verify a list within the Selected features group and click on Install.
Wait until the Microsoft Visual Studio Community 2015 is installed and the Setup Completed message is presented. You can monitor the progress of the installation and the downloading of necessary data using the Acquiring and Applying progress bars presented by the installer.
Microsoft Visual Studio Community 2015 allows you to develop various kinds of applications, not only solutions running on devices with the Windows 10 operating system. What is interesting is that it is also possible to develop applications for Android and iOS platforms using the same IDE, by applying the Xamarin platform. A set of suitable tools for this purpose can be installed by selecting the Cross Platform Mobile Development option while installing the IDE, as shown in the preceding screenshot (on the right). If you want to learn more about Xamarin, you could visit https://www.xamarin.com/ .
What is more, Microsoft Visual Studio Community 2015 also supports other types of applications, such as web and desktop applications, as well as allows to use various languages, including C#, C++, and even F#. If you want to learn more about the various possibilities of the IDE, let's take a look at https://www.visualstudio.com/ .
Of course, during the installation of the IDE, you can select more features than mentioned in this recipe. In such a case, apart from developing Windows 10-based solutions, you can use the same IDE for other development scenarios.
Microsoft Visual Studio Community 2015 is a really powerful and advanced IDE. However, it can be adjusted even further by a developer. For instance, one can easily show or hide particular windows as well as arrange them in a few variants, such as floating, docked, or tabbed. In this recipe, you will learn how to open additional windows and place them in suitable areas.
To use this recipe, you just need Microsoft Visual Studio Community 2015 installed, as explained in the previous recipe. No other prerequisites are required.
To arrange windows, you need to perform the following steps:
Launch Microsoft Visual Studio Community 2015.
To open an additional window, such as Solution Explorer or Class View, choose a suitable option from the View menu, as shown in the following screenshot:
To make a window floatable, either drag its title bar and drop it in the empty space, or choose the Float option from the context menu of the title bar.
To make a window docked, either drag its title bar and drop it in the location specified by the special indicator that appears on the screen, as shown in the following screenshot, or choose the Dock option from the context menu of the title bar.
It is important to prepare a suitable arrangement of windows that allows you to work with projects in a comfortable way. What is worth mentioning is that the arrangement of windows will automatically change in some special scenarios, such as debugging, and some new windows, strictly related to the given scenario, could appear on the screen. Their aim is to help a developer perform some specific tasks. You will learn how to run the application in the debug mode in the following part of this chapter.
Once you have the IDE installed, you can proceed to creating a new project. A project consists of a set of files that specify, for instance, the configuration of an application, or the design of particular pages, as well as code defining the interaction with the user interface.
To use this recipe, you just need Microsoft Visual Studio Community 2015 installed, as explained earlier in this chapter. No other prerequisites are required.
To create a new project, you need to perform the following steps:
Launch Microsoft Visual Studio Community 2015.
Navigate to File | New | Project... from the menu.
Click on the Installed group on the left-hand side. Then, navigate to Templates | Visual C# | Windows | Universal from the tree.
Select Blank App (Universal Windows) on the right-hand side, as shown in the following screenshot.
Type a name of the project (Name, such as
CH01
), choose a suitable location (Location), as well as type a name of the solution (Solution name).Click on OK. If an additional window with the possibility of choosing the target and minimum supported platform versions appears, choose proper values and click on OK. The project will then be created automatically.

It is worth mentioning the structure of the automatically generated solution to learn more about the various files that you will see while developing UWP applications for the Windows 10 platform. You could easily browse through the solution with the Solution Explorer window, which you can open by navigating to the View | Solution Explorer option from the menu.
The automatically generated structure of the solution is shown as follows:

At the top, you have the CH01 solution that contains only one project, also named CH01. Just after its name, there is an indicator that it is the Universal Windows project, thus it should work on various devices, such as smartphones, tablets, and desktops.
The first group within the project is named Properties. It contains two files, namely AssemblyInfo.cs
and Default.rd.xml
. This group provides information about the assembly with your application along with runtime directives. In most cases, you will not need to modify such files on your own.
The References group performs a very important role because it informs which additional references are used by the application. Such references may include your own class libraries or pre-prepared solutions available for developers. By using packages from the huge number of available ones, it is possible to significantly speed up development as well as limit the chance of introducing bugs while developing such software on your own. What is more, the IDE is supported by the NuGet Package Manager and can find and install packages. You will learn how to use it in the Creating and using a user control recipe in Chapter 2, Designing a User Interface.
The third group is named Assets and contains a set of images necessary for the application, such as for the splash screen, tiles, or logo. Of course, you need to prepare suitable graphics before submitting the application to the store.
The App.xaml
file uses the XAML language. You can use this file to define the resources that will be shared between various pages of the application, not to define them multiple times in various files, as shown in the Defining a global style recipe in
Chapter 2, Designing a User Interface. Apart from the App.xaml
file, there is the App.xaml.cs
file, which contains C# code handling a few scenarios regarding the application, such as its launching.
The MainPage.xaml
file is another file with XAML-based content. It represents the first page added automatically to the project. By default, it does not contain any controls, except a grid with a specified background color. You will learn more about this control in
Chapter 2, Designing a User Interface. Similarly, as in the case of the App.xaml
file, the MainPage.xaml
file is supported by the dedicated .xaml.cs
file, namely MainPage.xaml.cs
. It contains the C# code regarding this page.
Among other files, you can also find Package.appxmanifest
. It specifies the various properties regarding the application. You will take a look at the various settings available in this file in the Adjusting the manifest file recipe in
Chapter 9, Testing and Submission. At the end, it is worth mentioning the project.json
file with configuration of the project, including dependency to Microsoft.NETCore.UniversalWindowsPlatform
.
The Adding a new page recipe
The Arranging controls in a grid, Defining a global style, and Creating and using a user control recipes in Chapter 2, Designing a User Interface
The Creating the view model for a page recipe in Chapter 3, MVVM and Data Binding
The Adding a project to the Windows Dev Center, Associating an application with the store, and Adjusting the manifest file recipes in Chapter 9, Testing and Submission
While developing the application, it is necessary to run it to check whether it operates as expected. You can run the application on various devices, including a development machine, smartphone, or a set of emulators available within the IDE. In this recipe, you will learn how to build and run the application.
To run the application either on an emulator or on a real device, you need to perform the following steps:
Choose a proper configuration mode, either Debug or Release, from the drop-down list in the toolbar.
Tip
During development, the Debug configuration mode is recommended. However, it is also important to test the application in the Release mode before submitting it to the store.
Click on the small black arrow located in the toolbar, next to the option with the green triangle, as shown in the following image:
Choose a suitable option from the list:
Simulator: This is used to test the application in the dedicated simulator of tablets and desktops with the Windows 10 operating system and different screen sizes, from 7" to 27". It is also possible to easily check various touch modes, namely basic, pinch/zoom, and rotation.
Local Machine: This is used to test the application on the development machine currently used for development.
Remote Machine: This is used to test the application on the external device available in the network.
Device: This is used to test the application on a smartphone directly connected to the development machine.
Mobile Emulators: This is used to test the application on an emulator with various screen resolutions (WVGA, WXGA, 720p, 1080p, or QHD) and memory sizes (from 512 MB to 3 GB).
Each application contains pages with controls that allow the user to interact with the application. However, only one page is added to the project by default, so in this recipe, you will learn how to add another one.
To add a new page to the project, you need to perform the following steps:
Right-click on the project node in the Solution Explorer window and navigate to the Add | New Item... option from the context menu. The Add New Item window is opened.
Click on the Installed section on the left-hand side. Then, select Visual C# | XAML. Choose Blank Page on the right-hand side, as shown in the next screenshot.
Type a suitable name (Name) for the
.xaml
file, representing the new page. The.xaml.cs
file will be generated automatically. As an example, you could set the name asAboutPage.xaml
.

The files regarding the default page, both .xaml
and .xaml.cs
, are automatically added to the main directory. However, you do not need to place the files that represent the page here. You could locate such files in a dedicated directory, such as Views. You will learn how to create a new directory as well as place the .xaml
and .xaml.cs
files there in the Creating the view model for a page recipe in
Chapter 3, MVVM and Data Binding.
The Placing a control recipe
The Navigating between pages recipe
The Passing data between pages recipe
The Changing a default page recipe
The Creating the view model for a page recipe in Chapter 3, MVVM and Data Binding
The automatically generated page does not contain any content that could be interesting to a user. For this reason, it is important to learn how to place a new control.
By default, you have access to many controls that are available out of the box, such as a button, textbox, checkbox, list view, progress bar, calendar, or web view. Of course, these are only examples of the available controls. You can browse the full list in the Toolbox window within the IDE.
In this recipe, you will learn how to add the first button to the page.
To place a control on the page, you need to perform the following steps:
Double-click on the
MainPage.xaml
file in the Solution Explorer window.Open the Toolbox window by navigating to View | Toolbox from the menu.
Drag and drop the Button item from the Toolbox window to the graphical designer in the
MainPage.xaml
file. The control is now added, and you can easily adjust its location and size, as shown in the following image:

Adding controls by dragging them from the Toolbox window causes the creation of a suitable part of the XAML code. In the case of the exemplary button, the following code is generated automatically:
<Page
x:Class="CH01.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:CH01"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-
compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource
ApplicationPageBackgroundThemeBrush}">
<Button
x:Name="button"
Content="Button"
HorizontalAlignment="Left"
Margin="164,242,0,0"
VerticalAlignment="Top" />
</Grid>
</Page>
As you can see, the Button
control is added within Grid
. Its name is set to button
(x:Name
) and its content is set to the Button
text (Content
). Its location within the grid is specified by margins (Margin
), given in the following order: left (164 pixels), top (242 pixels), right (0 pixels), and bottom (0 pixels). What is more, horizontal and vertical alignments are set (HorizontalAlignment
and VerticalAlignment
, respectively).
The graphical editor available in Microsoft Visual Studio Community 2015 has a set of really useful features, such as the presentation of a UI for various screen resolutions. It is beneficial to learn more about such features in order to design a UI in a more efficient way.
The Handling events recipe
The Adding a button, Adding a text block, Adding a textbox, Adding a password box, Adding a checkbox, Adding a combobox, Adding a listbox, Adding an image, Adding controls programmatically, and Creating and using a user control recipes in Chapter 2, Designing a User Interface
Apart from adding controls to the page, it is necessary to introduce interaction with them, such as performing some actions after clicking on a button or choosing an item from a drop-down list. In this recipe, you will learn how to handle the event of pressing the button.
To use this recipe, you need the project from the previous recipe. It should contain the MainPage.xaml
file with the added button.
To handle the Click
event, you need to perform the following steps:
Double-click on the
MainPage.xaml
file in the Solution Explorer window.To generate a method that handles the situation of the button being pressed, double-click on the added button. Alternatively, click on the button (either in a graphical designer or the XAML code) and then double-click on the Click field in the Properties window with the Event handlers for the selected element option (the lightning icon) selected, as shown in the following screenshot:
Generating the method for handling the event of the button being clicked causes a modification, which is automatically introduced in both the MainPage.xaml
and MainPage.xaml.cs
files.
In the first file, with the XAML code describing the UI of the page, the Click
property is automatically added to the Button
element. It specifies the name of the method that is called when the user clicks on the button. The exemplary code is as follows:
<Page (...)>
<Grid (...)>
<Button
x:Name="button"
Content="Button"
HorizontalAlignment="Left"
Margin="164,242,0,0"
VerticalAlignment="Top"
Click="button_Click" />
</Grid>
</Page>
It is worth mentioning that the button_Click
method must exist in the MainPage
class (name set as x:Class
in the Page
element). This method is also automatically generated in the MainPage.xaml.cs
file, as follows:
private void button_Click(object sender, RoutedEventArgs e) { }
The method has a name that contains the name of the button (button
) as well as information about the kind of event (Click
). It has two parameters:
sender
: This is an object that represents the clicked element, which you can cast toButton
as(Button)sender
e
: This represents the additional arguments regarding the operation
To specify operations that should be performed after pressing the button, you just need to add suitable C# code as the body of the button_Click
method.
Tip
You could easily jump from the editor with the XAML code to the C#-based method definition by right-clicking its name defined in the .xaml
file (within Click
) and choosing Go To Definition from the context menu. Another solution is to click on such a name and press F12.
This way of handling the button being pressed is not the only possible one. Later in the book, you will learn how to use the data binding mechanism together with commands and the MVVM design pattern to improve the solution.
The Placing a control recipe
The Creating the view model for a page and Introducing bindings and commands recipes in Chapter 3, MVVM and Data Binding
It is quite difficult to imagine an application with only one page. Thus, it is crucial to know how to navigate from one page to another. In this recipe, you will learn how to navigate to another page after pressing the button as well as how to go back to the previous page after pressing the button on the other page.
To complete this recipe, you need the project with two pages, represented by the MainPage
and AboutPage
classes. Let's imagine that the first page operates as a main menu of the application with a set of buttons. After clicking on each of them, a user should be navigated to a particular page, such as with information about the company, with a list of products, or with contact data.
As an example, the Button
control should be added to both the pages, namely MainPage
and AboutPage
. However, they should present different content, such as About us (in MainPage
) and Go back (in AboutPage
), as graphically explained as follows:

To prepare an example that shows how to navigate between pages, you need to perform the following steps:
To navigate from
MainPage
toAboutPage
, modify the code of thebutton_Click
method in theMainPage.xaml.cs
file, as follows:private void button_Click(object sender, RoutedEventArgs e) { Frame.Navigate(typeof(AboutPage)); }
To go back to the previous page from
AboutPage
, modify the code of thebutton_Click
method in theAboutPage.xaml.cs
file, as follows:private void button_Click(object sender, RoutedEventArgs e) { if (Frame.CanGoBack) { Frame.GoBack(); } }
Navigation to another page is possible using the Frame
property of the Frame
type. It provides developers with a few methods, including Navigate
and GoBack
.
The first method (Navigate
) is used to navigate the user to another page with or without additional parameters (take a look at the next recipe), while the other (GoBack
) allows the user to go back to the previous page. In such a case, it is recommended that you check whether you can go back to the previous page by verifying whether the CanGoBack
property has a value equal to true
.
It is often necessary to pass some data from one page to another. It can be accomplished easily using another version of the Navigate
method, called on the Frame
property, as explained in this recipe.
To complete this recipe, you need the project with two pages, represented by MainPage
and ProductsPage
classes. The first page should contain the button with the Our products caption, while the other--the list of products and categories as well as the Go back button. The structure of pages is presented as follows:

It is worth mentioning that the page with products requires an identifier of the category, which should be presented. Such an identifier needs to be passed as a parameter. To show products and subcategories from the root category, 0
is passed. If you want to open a particular category, its identifier is passed instead, as shown on the right-hand side of the image.
To prepare an example that shows how to pass data between pages, you need to perform the following steps:
To pass an integer value (namely
0
) fromMainPage
toProductsPage
, modify the code of thebutton_Click
method in theMainPage.xaml.cs
file, as follows:private void button_Click(object sender, RoutedEventArgs e) { Frame.Navigate(typeof(ProductsPage), 0); }
To read the passed integer value, add the
OnNavigatedTo
method to theProductsPage.xaml.cs
file, as follows:protected override void OnNavigatedTo( NavigationEventArgs e) { base.OnNavigatedTo(e); int categoryId = (int)e.Parameter; List<string> products = GetProductsByCategory(categoryId); }
Note
To keep simplicity of the example, the scenario of showing a list of subcategories and products from a given category is not presented. If you want to develop it, you can use one of the items controls, as described in Chapter 3, MVVM and Data Binding.
Navigating to another page by passing a value is possible in a way that is similar to the approach presented in the previous recipe. However, in such a case, you should use another version of the Navigate
method with two parameters. The second is an object that is passed to another page. Of course, it could be an object of any type, not only an integer value as shown in the example.
A bit more explanation is necessary in the case of reading the parameter in the target page. To do so, you need to override the OnNavigatedTo
method, which has a parameter that is an instance of the NavigationEventArgs
class. Such a class contains the Parameter
property. However, it is not strongly typed, so you need to cast it to a suitable type, such as int
, as shown in the following code snippet:
int categoryId = (int)e.Parameter;
Apart from passing an integer, a floating point, or even string values, it is often necessary and convenient to pass more complex data, such as instances of user defined classes, between pages. This task can be achieved with the same approach as described in detail in the current recipe. Of course, you should not forget about specifying the values of particular properties of the class instance before passing it to another page as well as casting the parameter to a proper type in the code of the target page.
The UWP applications can be run on various devices that differ, for example, by availability of the back button. As you can see, such a button exists in the case of smartphones, but it is not available for tablets and desktops. Fortunately, it is possible to use the SystemNavigationManager
class to handle pressing the back button on a smartphone to navigate to the previous page in the application. What is more, the mechanism allows you to present the additional back button, at the top of the window, in case of a tablet or desktop-based version. You will learn how to do it in the current recipe.
To complete this recipe, you need the project with two pages, represented by the MainPage
and AboutPage
classes. Let's imagine that the first page operates as the main menu of the application with a set of menu items. After clicking on the first of them, the user should be navigated to the page with information about the company.
To handle the back button on a smartphone, as well as present an additional back button on tablets and desktops, you need to perform the following steps:
Specify the visibility of the additional back button (on devices without such a button), as well as handle an event of using it. To do so, modify the code of the
OnLaunched
method in theApp.xaml.cs
file, as shown as follows:protected override void OnLaunched( LaunchActivatedEventArgs e) { (...) if (rootFrame == null) { rootFrame = new Frame(); (...) Window.Current.Content = rootFrame; rootFrame.Navigated += (s, ev) => { SystemNavigationManager.GetForCurrentView() .AppViewBackButtonVisibility = ((Frame)s).CanGoBack ? AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed; }; SystemNavigationManager.GetForCurrentView() .BackRequested += OnBackRequested; } (...) }
Go back to the previous page when the back button is used, by adding the
OnBackRequested
method in theApp.xaml.cs
file, as shown as follows:private void OnBackRequested(object sender, BackRequestedEventArgs e) { Frame rootFrame = (Frame)Window.Current.Content; if (rootFrame.CanGoBack) { e.Handled = true; rootFrame.GoBack(); } }
By adding the necessary code directly in the App.xaml.cs
file, you do not need to specify the same operations in all .xaml.cs
files representing pages. The required lines of code are not very complicated and are explained in the following part of this recipe.
First of all, you handle the Navigated
event on an instance representing the frame (the roomFrame
variable of the Frame
type). When a user navigates to some page, the visibility of the back button is specified. Of course, it should be visible only when it is possible to go back from the current page, as specified in the following part of code:
SystemNavigationManager.GetForCurrentView() .AppViewBackButtonVisibility = ((Frame)s).CanGoBack ? AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed;
Then, you handle an event of the back button being clicked, namely BackRequested
. Of course, it supports a scenario of both pressing the hardware-based version and clicking on the additional back button added in the top-left corner of the window, as presented in the following screenshot of mobile and desktop-based versions:

When a user clicks on the back button, the OnBackRequested
method is called. Within it, you check whether it is possible to go back from the current page. In such a case, you indicate that the event is handled and call the GoBack
method. The operation of such a method is explained in detail in the Navigating between pages recipe.
By default, the automatically added page is shown after you launch the application. However, you may want to start with another page. Of course, such a change is possible and does not require significant modifications. You will learn how to do it in this recipe.
To step through this recipe, you need a project with two pages, represented by the MainPage
and DefaultPage
classes. Of course, you should manually add the second one.
To change a default page, shown when the application is launched, you need to perform the following steps:
Open the
App.xaml.cs
file by expanding theApp.xaml
node in the Solution Explorer window and double-clicking onApp.xaml.cs
.Take the line in the
OnLaunched
method (line #75):rootFrame.Navigate(typeof(MainPage), e.Arguments);
Change this line to the following:
rootFrame.Navigate(typeof(DefaultPage), e.Arguments);
Changing the default page requires a small modification in the App.xaml.cs
file, in the part related to the launching of the application. As you can see, such a part also uses the Navigate
method (on the Frame
instance), so changing the default page requires just a modification of its first parameter.
It is also possible to conditionally change the default page, for instance, depending on a value that indicates whether the user is currently logged in. The exemplary line of code is shown as follows:
rootFrame.Navigate(isLogged ? typeof(UserPage) : typeof(AnonymousPage), e.Arguments);
In this example, if the user is logged in (isLogged
equals to true
), the user will be navigated to UserPage
. Otherwise, AnonymousPage
is used instead.
While navigating from one page to another, the previous page is pushed to the back stack to allow the user to go back. However, in some scenarios, it could be necessary to programmatically read the back stack in order to know what the previously visited pages are. What is more, you can manually modify the back stack, for instance, to go back two pages instead of one. In this recipe, you will learn how to do it.
As an example, you will analyze the scenario presented in the following image:

On the dashboard (MainPage
), the user clicks on the Update data button. It navigates the user to UpdatePage
with the progress bar informing him/her about the progress of downloading necessary data. As soon as the download process is completed, the user is navigated to ResultsPage
with the Go back button. After pressing it, the user should go back directly to the dashboard, not to the previous page (UpdatePage
).
To use this recipe, you need a project with three pages, namely MainPage
, UpdatePage
, and ResultsPage
. On the first, you should place the Update data button navigating to UpdatePage
. Just as an example, the UpdatePage
could be equipped with the button, which will navigate the user to the last page. On ResultsPage
, let's place the Go back button. You should have an empty method handling the event of clicking on this button. Its code will be modified later in this recipe.
To modify the back stack to omit one page while going back, you need to perform the following steps:
Modify the body of the method handling clicking on the Go back button in the
ResultsPage.xaml.cs
file, as follows:if (Frame.BackStackDepth > 1) { Frame.BackStack.RemoveAt(Frame.BackStack.Count - 1); } if (Frame.CanGoBack) { Frame.GoBack(); }
Run the project and navigate from
MainPage
toUpdatePage
and toResultsPage
. Then, click on Go back and ensure that you have been navigated directly toMainPage
, not toUpdatePage
.
At the beginning, you check whether the back stack has a suitable number of elements, which is at least two. Only in such a case, you are able to skip one entry while going back. If the mentioned condition is satisfied, the last entry from the back stack is removed using the following line of code:
Frame.BackStack.RemoveAt(Frame.BackStack.Count - 1);
Then, it is necessary to go back using the GoBack
method, already explained in one of the previous recipes in this chapter.
The back stack performs a really important role while navigating between pages within an application. For this reason, it is beneficial to learn how it works and what information is stored in the back stack. You can check this with the following code snippet:
for (int i = 0; i < Frame.BackStack.Count; i++) { PageStackEntry entry = Frame.BackStack[i]; Type pageType = entry.SourcePageType; object pageParameter = entry.Parameter; }
This code fragment iterates through the back stack using the for
loop. In each iteration, you get a PageStackEntry
instance (named entry
) that contains various information about a visited page, such as its type and parameter.
Note
You can display a value while debugging using the code presented in the Logging information while debugging recipe.
In the exemplary scenario, analyzed in this recipe, the back stack contains two entries: regarding MainPage
(index 0) and UpdatePage
(index 1).
The provided emulators are equipped with some additional features that simplify the testing of applications. In this recipe, you will learn how to use such features of the smartphone-based emulators available within the IDE.
To utilize additional features provided by the emulator of a smartphone, you need to perform the following steps:
Select
Fit to Screen
to automatically adjust the size of the emulator. You could specify zoom directly using theZoom
option.Use the
Rotate Left
andRotate Right
options to rotate the emulator, either counterclockwise or clockwise, respectively.Check various input modes by clicking on the small icons located on the right-hand side of the emulator, such as:
Single Point Mouse Input
Single Point Touch Input
Multi-touch Input
Run the application in Mobile Emulator (...) WXGA 4.5 inch 1GB. Then, wait until the application is loaded.
Click on the
Tools
option (double arrow) to open the window with the additional features available within the emulator, which are organized into tabs, such as:Accelerometer: This is used to simulate data from the accelerometer sensor
Location: This is used to simulate the current GPS location
Screenshot: This is used to capture and save the screenshot from the emulator
Network : This is used to enable or disable the network for an emulator as well as to specify the network speed and signal strength
SD Card: This uses the local folder as an SD card within the phone
Checkpoints: This is used to manage the saving states of the emulator
Optional Settings: This is used to mark which hardware should be emulated
Notifications: This is used to simulate push notifications sent to the application
NFC: This is used to emulate NFC-based scenarios

The Running the application recipe
The Creating a unit test and Running a set of tests recipes in Chapter 9, Testing and Submission
Unfortunately, sometimes the prepared application does not work as expected. In such a case, it is useful to debug the solution to see how the application is executed. There are various ways of debugging, such as performing step-by-step execution or using breakpoints to stop the execution of a particular line of code. In this recipe, you will learn how to use both unconditional and conditional breakpoints.
To complete this recipe, you need the project with two pages, represented by the MainPage
and ProductsPage
classes. It is necessary to pass a category identifier while navigating from MainPage
to ProductsPage
.
To perform the breakpoints-based debugging, you need to follow the given steps:
Open the
ProductsPage.xaml.cs
file.To place an unconditional breakpoint, click on the gray margin on the left-hand side of the code line or click on the code line and press F9. As an example, you could place a breakpoint in the following line:
categoryName = categoryNames[categoryId];
Run the application in the emulator in the Debug mode by pressing F5 or by navigating to Debug | Start Debugging from the menu.
Navigate to the second page. The execution of the application should be stopped on the line of code with a breakpoint. Such a line is marked in the IDE with the yellow background, as shown as follows:
Place the mouse over
categoryId
to show a popup with the current value of the variable.To stop the execution of the application conditionally, right-click on the image of the breakpoint and choose the Conditions... option from the context menu. Then, specify the condition in the Breakpoint Settings window by providing the expression that must be evaluated to
true
to stop the execution, such as:categoryId > 0
Run the application in the emulator and see that its execution is stopped because the condition associated with the breakpoint is satisfied, as shown in the following screenshot:
The Step-by-step debugging recipe
The Executing code while debugging recipe
The Logging information while debugging recipe
The Creating a unit test and Running a set of tests recipes in Chapter 9, Testing and Submission
Debugging with breakpoints is a powerful technique that you can use to find a source of the problem in your applications. However, it is also useful to check its execution line by line. Of course, such a task can be accomplished by placing a breakpoint in each line, but this may be cumbersome for a developer. For this reason, this recipe will show you how to debug the application with step-by-step debugging.
To complete this recipe, you need the project with two pages, represented by the MainPage
and ProductsPage
classes. It is necessary to pass a category identifier while navigating from MainPage
to ProductsPage
. You should start the debugging of the project and stop it at any breakpoint.
To perform the step-by-step debugging, you need to perform the following steps:
To execute a single line and stop in the following line, press F10 or click on the Step Over icon in the toolbar. As a result, the next line will be marked with the yellow background, as shown in the following screenshot.
To step into a method that is called within the line, where debugging has stopped, press F11 or click on the Step Into icon in the toolbar.
To go to the line where the cursor is currently located, press Ctrl + F10 or choose the Run To Cursor option from the context menu of the line with the cursor.

The values of variables can be checked in a few ways, such as by placing the cursor over the name of the variable. However, when you want to see the values of a few variables in the following iterations within a loop, it is much more convenient to pin tooltips with their current values so they are automatically refreshed in each iteration. You can pin the tooltip by placing the cursor over the name of the variable and then pressing the pin icon. The exemplary result is shown in the preceding screenshot.
The Breakpoint-based debugging recipe
The Executing code while debugging recipe
The Logging information while debugging recipe
The Creating a unit test and Running a set of tests recipes in Chapter 9, Testing and Submission
When the execution of the application is stopped, you can easily check the values of the variables by moving the cursor over them. However, sometimes it may be useful to execute some parts of code, such as checking the length of a string. In such a case, you do not need to modify the application code and add some additional variables because you can use the Immediate Window feature that allows you to execute particular lines of code and present results. In this recipe, you will learn how to do this.
To complete this recipe, you need the project with two pages, represented by the MainPage
and ProductsPage
classes. It is necessary to pass a category identifier while navigating from MainPage
to ProductsPage
. You should start the debugging of the project and stop it at any breakpoint.
To execute some code while debugging, you need to perform the following steps:
Open Immediate Window by navigating to Debug | Window | Immediate from the menu.
Type an expression in Immediate Window and press Enter. The calculated result will be presented in the next line, as shown in the following screenshot:
The example from the screenshot you just saw shows a result of the following expression in Immediate Window:
formattedText.Length
It is evaluated using the values of the variables from the current state of debugging. In the example, the formattedText
variable is equal to Category #1 - Food & drinks.
, thus the string has 28 characters and such a result is shown in the window.
The next expression is as follows:
formattedText.ToUpper()
It presents the current value of the formattedText
variable, but in the uppercase version.
The Breakpoints-based debugging recipe
The Step-by-step debugging recipe
The Logging information while debugging recipe
The Creating a unit test and Running a set of tests recipes in Chapter 9, Testing and Submission
Sometimes, it is inconvenient to place many breakpoints in the code to see how the application, or its particular module, is being executed. In such a case, it is a good idea to log various information and present it to the developer in the IDE in real time.
In this recipe, you will learn how to perform such a task using the Debug
class from the System.Diagnostics
namespace as well as present logs in the IDE within the Output window.
To complete this recipe, you need the project with two pages, represented by the MainPage
and ProductsPage
classes. It is necessary to pass a category identifier while navigating from MainPage
to ProductsPage
.
To prepare an example that shows how to log some data while debugging, you need to perform the following steps:
Open the
ProductsPage.xaml.cs
file.To log information after clicking on the button, but before coming back to the dashboard, modify the code of the
Button_Click
method, as follows:private void Button_Click(object sender, RoutedEventArgs e) { Debug.WriteLine("Coming back to the dashboard"); Frame.GoBack(); }
Tip
Do not forget to add the
using
statement for theSystem.Diagnostics
namespace, using the following line of code:using System.Diagnostics;
The IDE is equipped with a really nice feature that allows you to automatically insert a missing
using
statement. To do so, just left-click on the name of the unrecognized type and press Ctrl+ . (dot). In the pop-up window, you can find an option to automatically add a properusing
statement.To add conditional logging, activated only if the associated Boolean expression is evaluated to
true
, modify the code of theOnNavigatedTo
method in theProductsPage.xaml.cs
file, as follows:protected override void OnNavigatedTo( NavigationEventArgs e) { (...) Debug.WriteLine($"Presenting a list of products from category #{categoryId}"); Debug.WriteLineIf(categoryId < 0, $"Incorrect category identifier, namely {categoryId}"); }
Start debugging the application.
Open the Output window by navigating to Debug | Windows | Output from the menu. Then, click on the button in the emulator to see how the logs appear in the Output window. The exemplary result is shown as follows:
Presenting a list of products from category #1 Coming back to the dashboard.
The Breakpoints-based debugging recipe
The Step-by-step debugging recipe
The Executing code while debugging recipe
The Creating a unit test and Running a set of tests recipes in Chapter 9, Testing and Submission
Applications, even for smartphones, can perform operations that intensively use resources. For this reason, it is possible that an application behaves differentially on various devices. This could lead to some problems with the operation, such as a poor user experience. With the usage of Microsoft Visual Studio Community 2015, a developer could measure CPU and memory usage in real time while running the application. In this recipe, you will learn how to use such a mechanism in your projects.
To monitor the CPU and memory usage while debugging the application, you need to perform the following steps:
Start debugging the application.
Open the Diagnostic Tools window by navigating to Debug | Show Diagnostic Tools from the menu.
Observe the process memory and CPU usage in charts, shown as follows:
The Diagnostic Tools window presents a set of useful information, not only about the used MB of the memory and percentage of CPU used. It also informs about moments when Garbage Collector (GC) is launched. What is more, you can see some steps of debugging, such as hitting a breakpoint.
It is really important to check the execution of the application on the slowest supported device to ensure that it will not have any problems with performance. Reaching the maximum acceptable values of CPU or memory usage is a sign that the code needs to be optimized. By modifying the code and checking its performance in an iterative way, you will see the impact of your changes on the final result.