Windows Phone 7 Silverlight Cookbook - Jonathan Marbutt - E-Book

Windows Phone 7 Silverlight Cookbook E-Book

Jonathan Marbutt

0,0
39,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Silverlight has revolutionized development using Microsoft technologies. It is an excellent tool for mobile application development. The XAML-based markup and familiar C# code are the perfect combination for building apps efficiently and with minimum hassle.Packed full of recipes containing comprehensive instructions for the tasks required to build modern compelling smartphone apps using Silverlight.Starting with application design and architecture, you will quickly move on to more technical features and APIs you can implement to make your app stand out. You will use the Camera API to scan barcode, location services to pinpoint the user’s GPS coordinates and accelerometer to provide feedback based on movement of the phone. All of these features can be provided in a slick user interface through the power of Silverlight. Animations, behaviors and XAML provide all you need and more.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 293

Veröffentlichungsjahr: 2011

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Windows Phone 7 Silverlight Cookbook
Credits
Foreword
About the Authors
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers and more
Why Subscribe?
Free Access for Packt account holders
Instant Updates on New Packt Books
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Layout and Design
Introduction
Downloading the tools
Understanding the tools
Visual Studio 2010 Express
Expression Blend for Windows Phone
Windows Phone Emulator
Also included in the download
Creating simple navigation
Getting ready
How to do it...
How it works...
There's more...
Using Positioning controls
Getting ready
How to do it...
How it works
Discovering the various input controls
Getting ready
How to do it...
How it works
There's more...
ViewStateManager introduction
Getting ready
How to do it...
How it works...
There's more...
Understanding the panorama control
Getting ready
How to do it...
How it works...
Using the pivot control
Getting ready
How to do it...
How it works...
2. Creating Animation
Introduction
Using ViewStateManager to create simple animations
Getting ready
How to do it...
How it works...
The basics of timelines
Getting ready
How to do it...
How it works...
There's more...
Using timelines for feedback to users
Getting ready
How to do it...
How it works...
3. Behaviors and Events
Introduction
Understanding events
Getting ready
How to do it...
How it works...
There's more...
Understanding basic behaviors
Getting ready
How to do it...
How it works...
There's more...
ControlStoryBoardAction
GoToStateAction
PlaySoundAction
Custom behavior
Getting ready
How to do it...
How it works...
There's more...
Physics engine behavior
Getting ready
How to do it...
How it works...
There's more...
4. DataBinding 101/MVVM
Introduction
A case for MVVM
Separation of Concerns
Testability
Reusability
Creating a simple model
Getting ready
How to do it...
There's more...
Creating a ViewModel
Getting ready
How to do it...
There's more...
Creating a view
Getting ready
How to do it...
How it works...
Element-to-element binding
Getting ready
How to do it...
How it works...
5. Services, Data, and RSS
Introduction
Creating a WCF service to access a SQL database
Getting ready
How to do it...
How it works...
There's more...
Using a WCF service in a Windows Phone application
Getting ready
How to do it...
How it works...
Building a simple RSS reader
Getting ready
How to do it...
How it works...
6. Location Services
Introduction
Tracking latitude and longitude
Getting ready
How to do it...
How it works...
See also
Tracking altitude, speed, and course
Getting ready
How to do it...
How it works...
There's more…
See also
Saving battery by using a location wisely
Getting ready
How to do it...
How it works...
See also
Using location services with the emulator
Getting ready
How to do it...
How it works...
There's more…
See also
Mapping your location
Getting ready
How to do it...
How it works...
7. Push Notifications to the Phone
Introduction
Updating the tile background without push
Getting ready
How to do it...
How it works...
There's more...
Creating a service to send notifications
Getting ready
How to do it...
How it works...
Registering for push notifications
Getting ready
How to do it...
How it works...
There's more...
See also
Creating a notifications helper
Getting ready
How to do it...
How it works...
See also
Creating toast notifications
Getting ready
How to do it...
How it works...
There's more...
Authenticated Push Notifications
8. Launchers and Choosers
Introduction
Automating e-mails
Getting ready
How to do it...
How it works...
Handling common About Us tasks
Getting ready
How to do it...
How it works...
Scanning barcodes
Getting ready
How to do it...
How it works...
There's more...
Debugging tips
Trigger happy Chooser
Enabling photo extras
How to do it...
How it works...
There's more...
Tombstoning
Getting ready
How to do it...
How it works...
There's more...
Methods of persisting state
Not all Launchers and Choosers are the same
Tombstone events
9. Sensing with Sensors
Introduction
Orienting your app
Getting ready
How to do it...
How it works...
There's more...
PortraitDown orientation
That mic is hot
Getting ready
How to do it...
How it works...
Accelerating your apps
Getting ready
How to do it...
How it works...
Developing the touch
Getting ready
How to do it...
How it works...
Shaking it up
Getting ready
How to do it...
How it works...
Pinching with ease
Getting ready
How to do it...
How it works...
There's more…
10. Preparing Apps for the Marketplace
Introduction
Configuring capabilities
Getting ready
How to do it...
How it works...
There's more...
Automated capabilities detection
Maintaining responsiveness
Getting ready
How to do it...
How it works...
Adding trial support
Getting ready
How to do it...
How it works...
There's more...
Creating iconography
Getting ready
How to do it...
How it works...
Submitting an app
Getting ready
How to do it...
How it works...
There's more...
Free app submissions
Getting paid
Download reports
Localization
Index

Windows Phone 7 Silverlight Cookbook

Windows Phone 7 Silverlight Cookbook

Copyright © 2011 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 authors, 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: August 2011

Production Reference: 1180811

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK

ISBN 978-1-849691-16-1

www.packtpub.com

Cover Image by Asher Wishkerman (<[email protected]>)

Credits

Authors

Jonathan Marbutt

Robb Schiefer Jr.

Reviewers

Cory Smith

Kelum Peiris

Tom McLeod

Acquisition Editors

David Barnes

Steven Wilding

Development Editor

Hithesh Uchil

Technical Editor

Pallavi Kachare

Copy Editor

Leonard D'Silva

Project Coordinator

Zainab Bagasrawala

Proofreader

Aaron Nash

Indexer

Monica Ajmera

Graphics

Geetanjali Sawant

Production Coordinator

Alwin Roy

Cover Work

Alwin Roy

Foreword

I am delighted that Jonathan and Robb undertook the task of writing this book. Both Jonathan and Robb have been involved in the .NET community for a number of years and developed a passion for the Windows Phone. With this book, they have decided to share their knowledge and experience with their readers to help developers dive into doing more with Windows Phone.

When we began rebuilding the Phone, the goal was to do this over multiple releases and keep iterating on feedback rapidly to take the platform forward. In doing so, the platform evolved with the developers consuming it and aligned to their needs. The premise of using platforms like Silverlight and XNA as the basis was founded by the need to make it simple and familiar, and also enable rapid development of a large volume of high quality applications. We also attempted to stitch together the end-to-end story Microsoft had to offer between the tools, the platforms, the phone operating system, and the various services in the company.

When I was approached to write this foreword by Scott Guthrie and Jonathan, I was personally skeptical given the risk of capturing so much in so little. By reading the book, I have personally had a refresher of the various constructs we have enabled over the year and feel that the authors have done a good job telling the end-to-end story.

The book embodies the basic construct of Windows Phone development, namely, to simplify and enable. Jonathan and Robb have taken the essence of what is required to get started and develop applications rapidly which is a key to mobile development. The market continues to evolve rapidly and hence the need for efficient development strategies including quick learning.

I hope the readers of this book learn and are able to develop high quality and attractive applications to help differentiate themselves in the highly competitive market.

Akhil Kaza

Development Manager Silverlight for Windows Phone

About the Authors

Jonathan Marbutt at the early age of ten, began to learn building simple games to amuse his friends and family. Twenty years later, he still has the passion for technology and development. Jonathan loves to share his passion with other developers by writing for his blog and various books as well as speaking at many user groups and technology conferences. Throughout the past three years, Jonathan's focus has primarily been on working with Silverlight and its most recent version for Windows Phone 7. Through this newest version for Windows Phone 7, Jonathan has been able to work on many high profile applications that are rated as some of the most downloaded applications.

Jonathan is also currently the Vice President and Co-founder of WayCool Software, Inc. based in Birmingham, AL which provides solutions for non-profit organizations. Jonathan has also been providing consulting services through his latest venture JM TechWare, Inc. where he helps provide both User Experience and architectural guidance on Silverlight, Windows Phone 7, and WPF applications. In addition to development, Jonathan has co-authored Visual Basic 2010 and .Net 4, published by Wrox Press.

Thank you to my beautiful wife Jennifer for being by my side while writing this book and putting up with the late nights that I worked to get it done. Thank you for supporting me and always being there for me. You are truly the love of my life.

Thank you to my precious little girl, Kathryn, for always brightening my day and making me enjoy the little things in life. Thank you for always making me laugh and always having a smile no matter what is going on. I love you so much and and love getting to be there to watch you grow up.

Thank you to my parents for encouraging me at an early age to pursue my passion and providing me the means to do so. I wouldn't be the person I am today without your help.

Robb Schiefer Jr. is a follower of Christ, husband to the perfect wife, and father of two beautiful girls. Coincidentally, he is also a successful .NET software developer which is a better qualification for writing a programming book.

His development career started while working part-time during college where he learned graphic design basics and built simple data-driven PHP websites. After college, he worked for a small startup on a VB6 application for educators and learned .NET by jumping head first into building a complimentary ASP.NET site. Since then, he has worked as a .NET developer for a market leading, privately held corporation with a global presence. This enterprise environment has provided many unique challenges and learning opportunities. He currently leads a development team in the company's latest development efforts, mentors many developers, and plays a leading role in planning the company's .NET architecture.

Prior to the announcement of Windows Phone 7, he had little experience with Silverlight, but always wanted to learn it. WP7 provided the perfect opportunity to learn Silverlight in a defined space and on a smaller scale. He currently has several apps in the marketplace and has plans for many more (if he ever gets this book done).

I would first like to thank my wonderful wife for her continual support and love (especially while writing the book). Also for her work at home with our two precious girls and in the future, number three. And four? I couldn't ask for a better wife, thank you and I love you. Second I would like to thank Jonathan for his friendship and for asking me to write the book with him. Lastly, thanks to the .NET/Silverlight/Windows Phone development community, Microsoft for finally having a decent smartphone OS which is a joy to work with and the followers of my blog.

About the Reviewers

Tom McLeod started writing software for fun 16 years ago and has been enjoying it ever since. He has written software for HP48 series calculators and a rainbow of UNIX flavors. Since earning a degree in trombone performance, he has worked on a variety of .NET projects. When he's not developing software, he enjoys producing episodes of The Deucecast podcast and being a father and photographer to his two young daughters. He can be contacted through leftylabs.com.

Kelum Peiris is a Mobile Software Developer with Polar Mobile, a company that provides an industry-leading platform to enable top-tier media publishers to easily and quickly launch mobile apps for every major Smartphone. At Polar Mobile, Kelum is primarily involved in developing the Windows Phone platform which will be used to deploy more than 500 apps in year 2011. He is a recent graduate from the University of Waterloo, Ontario, Canada where he specialized in Mobile Development and Real-Time Operating Systems. Kelum has a keen interest in advance concepts in Object Oriented Programming and Design Patterns and he is a clean code addict.

Colin Smith is an experienced mobile developer, musician, and startup guy currently working with a wide range of technologies. He is a co-founder and Mobile Lead of Cardinal, a startup focused on social music sharing, discovery, and analytics. He is currently the Technical Lead / Lead Developer of iOS applications at Shaw Communications as well. You may know him as Smixx, creator of the Developers rap song.

I'd like to thank my lovely wife Chelsea for putting up with the long hours and sleepless nights that went into reviewing this book while getting a startup off the ground and holding down a fulltime job as well, couldn't have done it without you!

www.PacktPub.com

Support files, eBooks, discount offers and more

You might want to visit www.PacktPub.com for support files and downloads related to your book.

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.

http://PacktLib.PacktPub.com

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books.

Why Subscribe?

Fully searchable across every book published by PacktCopy and paste, print and bookmark contentOn demand and accessible via web browser

Free Access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.

Instant Updates on New Packt Books

Get notified! Find out when new books are published by following @PacktEnterprise on Twitter, or the Packt Enterprise Facebook page.

I would like to dedicate this book to someone who didn't know anything about software development and often called me a nerd. For 23 years she lived life to the fullest and laughed louder than anyone in the world. To my sister Bebe, who went to be with the Lord. I love you.

Robb Schiefer Jr.

Preface

In this book, you will discover the latest development technology from Microsoft for the Windows Phone 7. We will cover all that you need to get a variety of applications developed. Throughout this book you will find many simple examples that stand by themselves to help provide quick reference to many of the common needs for a Windows Phone developer.

What this book covers

Chapter 1, Layout and Design, covers the most common ways to lay out your Windows Phone application that will provide you with the basics for designing applications. We will cover the basics of Expression Blend and its important role in Windows Phone Application development.

Chapter 2, Creating Animation, explains that understanding the basics of animations is no longer a tool just for designers, but it can play an important role in your application to give it the polish to make your application stand out from the crowd. Through this chapter, we will cover the basics of creating simple animations with both Storyboards and Visual State Manager.

Chapter 3, Behaviors and Events, explains now that you have the design aspects down for your application, it is time to give the user a way to interact with the application. In Windows Phone development, much of the initial interaction can be fired by both behaviors and events. We will show you some built in behaviors as well as developing custom behaviors.

Chapter 4, DataBinding 101/MVVM, covers the basic understandings of databinding in Silverlight as well as the MVVM design pattern as most apps have some data to populate and display. With MVVM, you can architect your application for much easier maintenance as well as easier testing and design time support for data.

Chapter 5, Services, Data, and RSS, explains that once you have a great understanding of how to structure an application to show data as well as the basics of databinding, it is now time to dig into pulling data from services. In this chapter, we will cover the basics of using WCF services as well as building a simple RSS reader.

Chapter 6, Location Services: Are you lost? Start using GPS coordinates and other location information from the phone in your apps with this chapter. We cover how to efficiently use location services, utilize the emulator for debugging your app, and using the built-in mapping control.

Chapter 7, Push Notifications to the Phone, shows how poling for data every 10 minutes is so 1995. This chapter covers setting up push notifications to the phone. Learn how the Microsoft Push Notification Services work and how you can leverage them to make your app the coolest on the block. Topics include start tile notifications, toast notification, and even a helper class to get you going faster.

Chapter 8, Launchers and Choosers, launches your app into Windows Phone 7 with tight integration through Launchers and Choosers. Start using the phone's core features like sending e-mails, starting up the web browser, and working with the camera or stored photos in this chapter. Learn how these APIs can be utilized with ease to make your app shine.

Chapter 9, Sensing with Sensors, covers the various sensor APIs to find what makes smartphones smart. Learn how to use the accelerometer, microphone, and touchscreen in your apps for a truly engaging end-user experience.

Chapter 10, Preparing Apps for the Marketplace: It's time to get rich and famous. It's time to share your app with the world in the Windows Phone Marketplace. Learn all the ins and outs of submitting an app to the marketplace and benefit from our experience. Topics include avoiding failed verifications, adding trial support, creating icons, and a step-by-step walkthrough of app submission.

What you need for this book

For this book, you will need the following:

Visual Studio Express for Windows PhoneExpression Blend for Windows PhoneWindows Phone SDK

The tools can be downloaded for free at http://developer.windowsphone.com.

Who this book is for

This book is for both the hobbyist and professional developer wanting to begin development for Windows Phone development. Throughout the book we tried to take the most simplistic approach for complex problems to provide you with the quickest reference to many common scenarios.

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text are shown as follows: "After finding the control in the assets window, drag-and-drop them onto your control.Blend."

A block of code is set as follows:

<VisualTransition GeneratedDuration="0:0:1"> <VisualTransition.GeneratedEasingFunction> <ExponentialEase EasingMode="EaseInOut"/> </VisualTransition.GeneratedEasingFunction> </VisualTransition>

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

<Storyboard> <DoubleAnimation Duration="0" To="26" Storyboard.TargetProperty="(FrameworkElement.Height)" Storyboard.TargetName="textBlock" d:IsOptimized="True"/> </Storyboard>

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "We need to create a new Windows Phone Application after clicking New Project in Visual Studio".

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via the subject of your message.

If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail <[email protected]>.

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 on www.packtpub.com/authors.

Customer support

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.

Downloading the example code

You can download the example code files for all Packt books you have purchased 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.

Errata

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 would 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/support, 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 on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright 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.

Questions

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 1. Layout and Design

In this chapter, we will cover:

Creating simple navigationUsing Positioning controlsDiscovering the various input controlsIntroduction to ViewStateManagerCustomizing ViewState of standard buttonsUnderstanding the panorama controlUsing the pivot control

Introduction

When Microsoft announced the Windows Phone 7, they made a bold move to drop the legacy of Windows CE. By doing this, they decided to leverage Silverlight as the foundation of their mobile user interface. Many people relate Silverlight with applications that have been used for events such as the Olympics to deliver high definition videos. What most people don't realize is that the real power of Silverlight is to develop rich applications that go beyond the traditional Windows Forms type development. With Silverlight, they have built-in rich support for both designers and developers to build applications together in environments that they are both familiar with.

Microsoft also took another bold move in the tooling by providing both Expression Blend 4 and Visual Studio 2010 for Windows Phone for free. This choice was to give developers and designers the easiest way to begin developing for Windows Phone 7. Both of these tools provide a rich atmosphere to spark creativity among designers while giving developers the tools to get the job done.

In this chapter, we will familiarize ourselves with the basic tools of developing a Windows Phone 7 Silverlight Application. These skills will help you throughout the rest of the book by giving you the fundamentals for building any Silverlight Application on Windows Phone 7.

Downloading the tools

Before you begin to write your first line of code or design your first user interface for Windows Phone 7, you will need to download and install the Visual Studio and Expression Blend. These tools are offered completely free by Microsoft and can be downloaded at http://developer.windowsphone.com. You will also need the latest version of the Zune software if you will test your application on a physical device. The Zune software can be downloaded from http://www.zune.net/en-us/products/software/download/.

Understanding the tools

There are several pieces to the tools that you will download, and each serve their own role.

Visual Studio 2010 Express

Visual Studio 2010 Express provides an environment that is especially designed for the programming side of an application. This doesn't mean that if you are a designer you shouldn't use Visual Studio, but use it to supplement your skills with Blend. There are many areas that Visual Studio offers that Blend does not offer, including:

InteliSense: If you have ever used Visual Studio, then you will be familiar with this feature. This provides you with very rich auto complete features when you are typing in the code behind files.Debugging: Visual Studio provides many advance debugging features that aren't offered in Blend. This includes the ability to set break points to step through your code while it is running. Visual Studio also provides the ability to debug your application on the phone versus the emulator whereas Blend does not allow breakpoint support for debugging.

Expression Blend for Windows Phone

Microsoft Expression Blend for Windows Phone offers a tool that is more intended for the designing of user interfaces. While Visual Studio does provide drag-and-drop type design for user interfaces, there are many areas that Visual Studio is not well suited for, including:

Animation: Expression Blend provides a variety of ways to create simple and complex animations. Or if you have been using Adobe Flash or other animation tools, this will be very familiar to you as Blend uses Timeline-based animations as well as other transition types.Vector-graphics support: Expression Blend also provides a vector-graphics support for creating your UI. Microsoft has also included support for importing existing assets from Adobe Illustrator and Photoshop.Visual state editing: Blend provides a simple interface for setting visual states on controls that Visual Studio does not.Template editing: Blend also offers a rich interface for editing templates and creating templates without having to know how to do it in the code.Sample data: The sample data features of Blend allow you to quickly mock up user interfaces that might be attached to a database and see how the controls look without having the actual database connection in place.

The many features of Expression Blend create an environment for developing rich user experiences on Windows Phone. It is an essential tool for both the developers and designers and comfortable for them to use too.

Windows Phone Emulator

The Windows Phone Emulator provides you with a virtual machine that emulates the Windows Phone operating system. This is used to provide a test environment that is almost identical to the runtime of the phone devices.

Also included in the download

There are several other items included in the download that enable you to run the items above to develop Windows Phone applications; these include:

Silverlight 4 SDK.NET Framework 4XNA Game Studio 4.0

The XNA Game Studio is an extensive technology that is created for developing more complex games and will not be covered in this book. The XNA framework is an alternative library for building Windows Phone 7 applications. It doesn't support the layout controls and event-driven input suitable for line-of-business applications, but uses input and graphics methods useful for more complex games. Because of the extent of the XNA framework, it will not be covered in this book but see http://msdn.microsoft.com/en-us/wp7trainingcourse_wp7xna_unit.aspx for some great example on getting started with XNA.

Creating simple navigation

If you are developing a Windows Phone application, the odds are you will have more than one page which you want to show to the user. Luckily for us, Microsoft has provided a basic navigation framework for navigating from one screen to another. This type of navigation is very similar to how you would navigate from one web page to another. It supports query strings similar to websites. This simple navigation example will be used throughout the book as a starting point for many other examples. This is a popular way to build applications that a user can easily navigate.

We will create a business information application that simply displays information about a fictional company called ACME and allows you to navigate from one screen to another easily. We will include the following pages:

HomeAbout ACMEContact ACMELocations
Corporate OfficeSatellite Office

Although this application is very simple, it is designed to give you the fundamental building blocks for creating a complex Windows Phone application.

Getting ready

Before we begin, we need to create a new Windows Phone Application after clicking New Project in Visual Studio:

How to do it...

Now that you have created the Navigation Project, in the following example, you will see the basic structure of the application on the right-hand side of Visual Studio:

Add some folders to the structure of the application by right-clicking on the NavigationExample project in the Solution Explorer, selecting Add | New Folder, and then renaming the folder as Views.

Now, to add the first pages to the application, right-click on the new Views folder, select Add | New Item, then select the Windows Phone Portrait page, enter About.xaml as the name, and click OK.Repeat this step for the Contact page, naming it as Contact.xaml:We will then repeat steps 1 and 2 for creating a sub folder named Locations under the Views folder and adding two more Windows Phone Portrait pages named CorporateOffice.xaml and SatelliteOffice.xaml. This will create a project that should look like this:

In the previous steps, we had only spent time in Visual Studio. Now it is time to swap over to Expression Blend. OK, so you may be asking yourself, "Can't I just stay in Visual Studio?". The answer is yes you can, but you will find it much easier to do many of the design-related items like adding controls and setting properties of controls in Blend. The good news is that Blend and Visual Studio both use the same project files, so you can leave both Visual Studio and Blend open with the same project and they will update each other when you save the files:

To open this project in Blend, right-click on the MainPage.xaml and select Open in Expression Blend….The first things you will want to change are the two TextBlocks at the top of the page. To do this, simply double-click on the text to begin editing the text on the top-most label and enter the text ACME Co.. Then double-click the larger TextBlock and type Home.Now that we have the home page labels renamed, let's do the same thing for the sub pages by double-clicking on them in the solution explorer, double-clicking the TextBlocks, and entering appropriate titles. For the Corporate Office page, enter ACME Co. as the upper title and Corporate Office in the larger TextBlock. Also do this for the Satellite Office page.What we want to do now is provide a basic navigation of the MainPage.xaml to the About, Contact, and Location Pages by using the HyperlinkButton control. We do this by clicking the assets button at the bottom of the tool box on the left-hand side of Blend. This will expand and give you a search box where you can search for HyperLinkButton:

After finding the control in the assets window, drag-and-drop them onto your control.Blend.

Once you have the hyperlinks on your design surface, double-click on them to edit the text of the first one as About, the second as Contact, and the last one as Locations. This should create a screen that looks like the following:Enable each of these links to navigate to the corresponding pages when a user touches the link on the phone. This is easily done by selecting the hyperlink button, and then on the properties window setting the NavigationUri property to the corresponding page, as seen in the following screenshot:In this example, we are selecting the NavigationUri for the About button. Simply select the About.xaml. Repeat this step for the Contact and Locations links.Now run the application by hitting F5. You can now see that clicking on the items in the emulator navigates to the corresponding pages in your application. This includes using the back button that is located on the phone.

How it works...

This simple form of navigation works by utilizing the underlying navigation framework built into the application. In Silverlight, pages are defined in the System.Windows.Controls.Page class. The Windows Phone Portrait Page items you added to the solution are instances of a subclass of the type, Microsoft.Phone.Controls.PhoneApplicationPage. It defines phone-platform-specific events and properties including the BackKeyPress event, which is raised when the phone's hardware back button is pressed.

When you set the NavigationUri property of each link, what is actually happening is that it is setting this property in the XAML, as you can see in the following code:

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <HyperlinkButton Content="About" Grid.Row="1" NavigateUri="/NavigationExample;component/Views/About.xaml"/> <HyperlinkButton Content="Contact" Grid.Row="2" NavigateUri="/NavigationExample;component/Views/Contact.xaml"/> <HyperlinkButton Content="Locations" Grid.Row="3" NavigateUri="/NavigationExample;component/Views/CompanyLocations. xaml"/> </Grid>

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased 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.

As you can see, it doesn't just set the NavigationUri