41,99 €
Discover over 125 solution-based recipes to help you build applications for smartphones, tablets, and desktops
The book is dedicated to programmers with various experience of developing applications for Windows-based smartphones, tablets, and desktops—even beginners can find suitable content.
Need to ensure you can always create the best Windows apps regardless of platform? What you need are solutions to the biggest issues you can face, so you can always ensure you're making the right choices and creating the best apps you can.
The book starts with recipes that will help you set up the integrated development environment before you go ahead and design the user interface. You will learn how to use the MVVM design pattern together with data binding, as well as how to work with data in different file formats.
Moving on, you will explore techniques to add animations and graphics to your application, and enable your solution to work with multimedia content.
You will also see how to use sensors, such as an accelerometer and a compass, as well as obtain the current GPS location. You will make your application ready to work with Internet-based scenarios, such as composing e-mails or downloading files, before finally testing the project and submitting it to the Windows Store.
By the end of the book, you will have a market-ready application compatible across different Windows devices, including smartphones, tablets, and desktops.
This quick-start book takes a cookbook format with recipes covering more than 125 solutions to help you create and build applications for Windows 10. The examples presented in the book use the free integrated development environment. A supporting set of codes that present solutions to problems described in particular chapters is available as well.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 493
Veröffentlichungsjahr: 2016
Copyright © 2016 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: December 2016
Production reference: 1141216
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78646-772-0
www.packtpub.com
Author
Marcin Jamro
Copy Editors
Gladson Monteiro
Muktikant Garimella
Reviewer
Melania Andrisan
Project Coordinator
Izzat Contractor
Commissioning Editor
Kunal Parikh
Proofreader
Safis Editing
Acquisition Editor
Chaitanya Nair
Indexer
Rekha Nair
Content Development Editor
Rohit Singh
Graphics
Jason Monteiro
Technical Editor
Pratish Shetty
Production Coordinator
Shraddha Falebhai
Marcin Jamro, PhD, is an entrepreneur and researcher as well as a developer and architect of various kinds of application, such as web, mobile, and distributed ones. He is interested in many aspects of computer science, including software engineering and project management. Marcin is passionate about C#, C++, and C languages in general, design patterns, new technologies, and mobile devices, especially the Windows platform.
He has significant practical experience in project development and holds the position of the President of the Board at TITUTO Sp. z o.o. [Ltd.] in Rzeszów, Poland. His company develops various IT projects, including mobile and web applications. To add to this, TITUTO Sp. z o.o. [Ltd.] has a set of its own products dedicated to hotels and tour operators. You can read more about them at http://tituto.com.
Marcin has published several papers, taken part in many conferences, organized a few of them, and participated in two internships at Microsoft in Redmond, USA. He has Microsoft Certified Professional, Microsoft Certified Technology Specialist, and Microsoft Certified Professional Developer certificates.
You can find out more about Marcin on his website, http://jamro.biz, and you can easily contact him by sending an e-mail to [email protected].
I would like to dedicate this book to my parents – Dorota and Jozef.
Of course, I cannot forget the employees at Packt for their support while writing this book. I would like to thank the reviewer for her valuable feedback regarding the content and for pointing out the topics that required additional clarification or modification. Last but not least, I would really want to thank you for reading this book. I hope that you will enjoy it and it will become a source of useful knowledge when developing applications for various platforms with the Windows 10 operating system.
Melania Andrisan was interested in technology from an early age, so pursuing computer science was a natural fit for her. During college in Timisoara, she was involved in a lot of Microsoft-related community events, discussing topics such as WPF, Silverlight, and ASP.NET. Her involvement continued after joining the Haufe Group as she talked at various national and international developer conferences about Microsoft-related technologies. For Haufe Group, Melania is part of Haufe Group's CTO office as a Cross Domain Solution Architect and she has architected several of their internal and consumer-facing projects. At the moment, she is a proud mother of a little girl, but she's eager to get back to work soon.
You can find out more about Melania on her website, http://mela.ro or on Twitter at @melaniadanciu.
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Nowadays, there are various types of devices available on the market, such as smartphones, tablets, and desktops. You can use them every day to perform common tasks, such as browsing the Internet, sending e-mail messages, recording movies, sharing photos using social media, and playing games. It is not unusual to use even more than one device, for instance, a smartphone, which we carry in our pockets almost all the time, a tablet that we use to perform various tasks at home, and a desktop at work. Of course, these devices can differ significantly from each other not only in terms of screen resolution, but also about available sensors and performance. However, does it mean that you cannot develop your own application for all of them in a simple way? Do you need to create a separate application from scratch for smartphones, tablets, and desktops?
If such devices use the Windows 10 operating system, the answer to both these questions is no! This platform allows you to develop a Universal Windows Platform (UWP) application that can be run on various device families. Such a task is really simplified because you can use the same programming language, technologies, as well as the Integrated Development Environment (IDE).
Despite supporting a wide range of devices, the UWP applications can be equipped with an attractive User Interface (UI) created using the Extensible Application Markup Language (XAML). With the availability of a set of predefined controls and animations, your work can be significantly reduced. What is more, you can take advantage of the Model - View - ViewModel (MVVM) design pattern and data binding to improve quality of the code and make its maintenance easier. The UWP applications can also use multimedia, read data from built-in sensors, and store data in various ways. Internet-based scenarios are supported and you can also download a file or get data from an Application Programming Interface (API). Many devices allow obtaining the current Global Positioning System (GPS) location, which can be used to show a marker in a suitable place on the map or to launch the GPS-based navigation. When the solution is developed, it can be submitted to the Windows Store. Thus, it can be downloaded and used by people all over the world!
Are you ready to learn how to develop an application for Windows 10-based smartphones, tablets, and desktops? If so, let’s start reading and writing the code!
Chapter 1, Getting Started , presents setting up a suitable IDE, creating a project, adding pages to the application, designing a user interface, and handling navigation. You will learn how to run the application in an emulator and on a real device as well as how to debug it and measure performance.
Chapter 2, Designing a User Interface , shows how to design pages using various controls, such as textboxes and buttons, as well as how to arrange them in various variants, either vertically, horizontally, or in a grid. You will also get to know how to prepare user controls, apply styles, localize the project, and prepare dedicated versions of pages for various device families.
Chapter 3, MVVM and Data Binding , covers the application of the MVVM design pattern, which divides the project into three parts, namely, model, view, and view model. The topic of the data binding mechanism, together with commands, is also taken into account. You will see how to display a collection of items and how to use value converters.
Chapter 4, Data Storage , deals with managing directories and files along with writing and reading a few types of files, such as with plain text, XML, and JSON-formatted content, as well as binary files with content in the user-defined format. You will also learn how to use a SQLite database in your application.
Chapter 5, Animations and Graphics , explains how to improve the user interface by introducing animations. They can be applied to display a control as well as change its size, position, or even rotation. This chapter also shows how to handle a few touch events and introduces the topic of rendering 3D graphics using DirectX, XAML, and C++ language.
Chapter 6, Multimedia , describes how to support multimedia content in an application, such as by playing a movie clip, listening to an audio file, and presenting a collection of photos. The subject of modifying images in a programmatic way is also taken into account. You will see how to take an image or record a movie using a camera, scan QR codes, and synthesize and recognize speech.
Chapter 7, Built-in Sensors , presents how to use various sensors to obtain a set of data, such as G-force values using an accelerometer, a heading of magnetic north using a compass, a current value of ambient light using a light sensor, as well as a current orientation of a device. To add to this, you will learn how to control vibrations of a phone and how to obtain the current GPS location.
Chapter 8, Internet-based Scenarios , covers various scenarios related to the Internet, such as opening a website, composing an e-mail message, as well as opening a map in the external tool and directly in your application. You will also see how to get and send some data to an API, as well as how to download files from the Internet.
Chapter 9, Testing and Submission , introduces unit testing and the process of configuring and submitting the project to the Windows Store. You will get to know how to adjust the configuration, prepare the necessary files, submit and update the application, as well as browse reviews and ratings regarding the published application.
This book presents development of UWP applications for various devices running on the Windows 10 operating system. Thus, you need a set of tools that allow designing the user interface, writing supporting code, as well as running the application and testing it. Fortunately, all of these features are available in the Microsoft Visual Studio Community 2015, which you can use while reading this book. The process of its installation and configuration is presented in detail in Chapter 1, Getting Started .
To step through all recipes presented in this book, especially to publish an application in the Windows Store, it is necessary to have a developer account. What is more, it is recommended to have a real smartphone or tablet with the Windows 10 operating system to test the developed applications on a real device. If you do not have one, you can use the built-in emulators, but not all recipes can be checked in practice.
The book is dedicated to programmers with various experience in developing applications for Windows-based smartphones, tablets, and desktops. Thus, even beginners can find suitable content to learn how to develop their first application!
However, it is recommended to have some basic knowledge of the C# language and object-oriented programming to understand code snippets presented in the book. Prior experience in developing mobile and desktop applications and using the XAML language is not necessary.
This book is organized in the form of solution-based recipes to present various features that could be interesting for developers. To make it even more useful, the code is attached to each chapter. Thus, you can easily download the code and run the application without the need of typing the code on your own.
It is worth mentioning that some code has been simplified. For this reason, it could differ from the best practices and may have significantly limited, or even removed, security checks and functionalities. Before publishing your application, it should be thoroughly tested to ensure that is works correctly in various circumstances.
In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There's more..., and See also).
To give clear instructions on how to complete a recipe, we use these sections as follows:
This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "The files regarding the default page, both .xaml and .xaml.cs, are automatically added to the main directory."
A block of code is set as follows:
private void button_Click(object sender, RoutedEventArgs e) { Frame.Navigate(typeof(ProductsPage), 0); }When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
private void button_Click(object sender, RoutedEventArgs e) { if (Frame.CanGoBack) { Frame.GoBack(); } }New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Verify a list within the Selected features group and click on Install."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome. Let us know what you think about this book--what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Windows-Application-Development-Cookbook. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from http://www.packtpub.com/sites/default/files/downloads/WindowsApplicationDevelopmentCookbook_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
In this chapter, we will cover the following recipes:
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!
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:
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.
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:
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:
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:
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.
You can open the graphical configuration tool by double-clicking on the Properties group.
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.
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 step through this recipe, you only need the automatically generated project.
To run the application either on an emulator or on a real device, you need to perform the following steps:
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.
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 step through this recipe, you only need the automatically generated project.
To add a new page to the project, you need to perform the following steps:
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 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 step through this recipe, you only need the automatically generated project.
To place a control on the page, you need to perform the following steps:
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).
Try to adjust the values of Margin, HorizontalAlignment, and VerticalAlignment on your own to get to know the impact of such properties on the button layout. You will learn more about various ways to place controls in the next chapter.
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.
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:
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:
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.
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.
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:
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.
