Tải bản đầy đủ (.pdf) (1,153 trang)

101 Windows Phone 7 Apps doc

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (24.21 MB, 1,153 trang )

www.it-ebooks.info
800 East 96th Street, Indianapolis, Indiana 46240 USA
Adam Nathan
101 Windows
®
Phone 7 Apps,
VOLUME I: DEVELOPING APPS 1-50
www.it-ebooks.info
101 Windows® Phone 7 Apps,Volume I
Copyright © 2011 by Adam Nathan
All rights reserved. No part of this book shall be reproduced, stored in a retrieval
system, or transmitted by any means, electronic, mechanical, photocopying, record-
ing, or otherwise, without written permission from the publisher. No patent liability is
assumed with respect to the use of the information contained herein. Although every
precaution has been taken in the preparation of this book, the publisher and author
assume no responsibility for errors or omissions. Nor is any liability assumed for
damages resulting from the use of the information contained herein.
ISBN-13: 978-0-672-33552-5
ISBN-10: 0-672-33552-2
Library of Congress Cataloging-in-Publication Data
Nathan, Adam, 1977-
101 Windows phone 7 apps / Adam Nathan.
v. cm.
Includes index.
Contents: v. 1. Developing apps 1-50.
ISBN-13: 978-0-672-33552-5 (v. 1)
ISBN-10: 0-672-33119-5 (v. 1)
1. Application software—Development. 2. Windows phone (Computer file) 3.
Smartphones—Programming. 4. Mobile computing. I.Title. II. Title: One hundred one
Windows phone 7 apps.
QA76.76.A65N378 2011


004.165—dc22
2011010335
Printed in the United States of America
First Printing April 2011
Trademarks
All terms mentioned in this book that are known to be trademarks or service marks
have been appropriately capitalized. Sams Publishing cannot attest to the accuracy of
this information. Use of a term in this book should not be regarded as affecting the
validity of any trademark or service mark.
Warning and Disclaimer
Every effort has been made to make this book as complete and as accurate as possi-
ble, but no warranty or fitness is implied.The information provided is on an “as is”
basis.The author(s) and the publisher shall have neither liability nor responsibility to
any person or entity with respect to any loss or damages arising from the information
contained in this book or from the use of the programs accompanying it.
Bulk Sales
Sams Publishing offers excellent discounts on this book when ordered in quantity for
bulk purchases or special sales. For more information, please contact
U.S. Corporate and Government Sales
1-800-382-3419

For sales outside of the U.S., please contact
International Sales

EDITOR-IN-CHIEF
Greg Wiegand
EXECUTIVE EDITOR
Neil Rowe
DEVELOPMENT EDITOR
Mark Renfrow

MANAGING EDITOR
Kristy Hart
PROJECT EDITOR
Betsy Harris
SENIOR INDEXER
Cheryl Lenser
PROOFREADER
Apostrophe Editing
Services
TECHNICAL EDITOR
Dave Relyea
PUBLISHING
COORDINATOR
Cindy Teeters
BOOK DESIGNERS
Gary Adair
Adam Nathan
COMPOSITOR
Bronkella Publishing LLC
www.it-ebooks.info
Introduction 1
part I getting started
1 Tally (App Basics) 17
2 Flashlight (Application Bar) 39
3 In Case of Emergency (Orientation & Keyboards) 61
4 Stopwatch (Grid & User Controls) 89
5 Ruler (Canvas & Vector Graphics) 123
6 Baby Sign Language (Page Navigation & Data Binding) 153
7 Date Diff (Silverlight for Windows Phone Toolkit) 185
8 Vibration Composer (Vibration & Running While Locked) 191

9 Fake Call (Resources & Styles) 207
10 Tip Calculator (Application Lifecycle & Control Templates) 235
11 XAML Editor (Dynamic XAML & Popup) 271
part II transforms & animations
12 Silly Eye (Intro to Animation) 301
13 Metronome (Intro to 2D Transforms) 327
14 Love Meter (Keyframe Animations) 347
15 Mood Ring (Color, Object & Point Animations) 361
16 Lottery Numbers Picker (Sharing Animations) 377
17 Pick a Card Magic Trick (3D Transforms) 395
18 Cocktails (Quick Jump Grid) 413
19 Animation Lab (Custom Controls & VSM) 441
contents at a glance
www.it-ebooks.info
part III storing & retrieving local data
20 Alarm Clock (Settings,Toggle Switch, Custom Font) 463
21 Passwords & Secrets (Encryption & Observable Collections) 493
22 Notepad (Reading & Writing Files) 527
23 Baby Milestones (Reading & Writing Pictures) 545
24 Baby Name Eliminator (Local Databases & Embedded Resources) 565
25 Book Reader (Pagination & List Picker) 587
part IV pivot, panorama, charts, & graphs
26 TODO List (Pivot & Context Menu) 611
27 Groceries (Panorama) 649
28 Alphabet Flashcards (Filmstrip-Style Swiping) 675
29 Weight Tracker (Charts & Graphs) 681
part V audio & video
30 Cowbell (Sound Effects) 711
31 Trombone (Sound Manipulation) 719
32 Local FM Radio (Radio Tuner) 731

33 Subservient Cat (Video) 743
part VI microphone
34 Bubble Blower (Sound Detection) 759
35 Talking Parrot (Recording & Playing) 775
36 Sound Recorder (Saving Audio Files & Playing Sound Backward) 797
Contents at a Glance
iv
www.it-ebooks.info
part VII touch & multi-touch
37 Reflex Test (Single Touch) 827
38 Musical Robot (Multi-Touch) 839
39 Paint (Ink Presenter) 847
40 Darts (Gesture Listener & Flick Gesture) 875
41 Deep Zoom Viewer (Pinch, Stretch, & Double Tap Gestures) 897
42 Jigsaw Puzzle (Drag Gesture & WriteableBitmap) 913
43 Spin the Bottle! (Rotate Gesture & Simulating Inertia) 945
part VIII accelerometer tricks
44 Boxing Glove (Accelerometer Basics) 951
45 Coin Toss (Throw) 965
46 Noise Maker (Shake) 981
47 Moo Can (Turn Over) 993
48 Level (Determining Angle) 1007
49 Balance Test (2D) 1019
50 Pedometer (Walking Motion) 1035
part IX appendices
A Lessons Index 1049
B XAML Reference 1059
C Theme Resources Reference 1073
D Animation Easing Reference 1083
E Geometry Reference 1089

Index 1097
Contents at a Glance
v
www.it-ebooks.info
Progress Bar
Visibility
Orientation Lock
5 Ruler 123
Canvas
Vector Graphics
Slider
Repeat Button
Hardware Back, Start, & Search
Buttons
Hit Testing
Content Controls
6 Baby Sign Language 153
Page Navigation
Data Binding
Data Templates
List Box
Image
Resource Versus Content Build
Actions
7 Date Diff 185
Silverlight for Windows Phone
Toolkit
Date Picker
8 Vibration Composer 191
Vibration

Wrap Panel
Running While the Screen is
Locked
Getting Coordinates of an
Element
The Tag Property
Line Breaks
Introduction 1
part I getting started
1 Tally 17
The Application Manifest
Capabilities
Icons
Splash Screen
XML Namespaces
Status Bar
Phone Theme Resources
Naming XAML-Defined Elements
Button
2 Flashlight 39
Application Bar
Timers
Brushes
Message Box
3 In Case of Emergency 61
Orientation
On-Screen Keyboard
Hardware Keyboard
Text Box
Input Scopes

Scroll Viewer
Size Properties
Margins and Padding
Emulator-Specific Code
4 Stopwatch 89
Grid
StackPanel
User Controls
Alignment
table of contents
www.it-ebooks.info
14 Love Meter 347
Keyframe Animations
Animating Scale
Checking Storyboard Status
15 Mood Ring 361
Color Animations
Property Paths
Gradient Brushes
Object Animations
Point Animations
Drop Shadows
16 Lottery Numbers Picker 377
Sharing Animations
Creating Animations in C#
Looping Selector
17 Pick a Card Magic Trick 395
3D Transforms
Opacity Masks
Image Brush

One-Time Actions
18 Cocktails 413
Quick Jump Grid
Dependency Properties
URL Encoding & Decoding
Storyboards as Timers
Indeterminate Progress Bars
Long List Selector
19 Animation Lab 441
Custom Controls
Visual State Manager
Bitmap Caching
Tilt Effect
9 Fake Call 207
Resources
Styles
Time Picker
Text Line Height
Disabling Automatic Screen Lock
10 Tip Calculator 235
Application Lifecycle
Control Templates
Routed Events
Theme Detection
Toggle Button, Radio Button,
& Check Box Controls
List Box Items
Data Binding to a Named Element
11 XAML Editor 271
Dynamic XAML

Popup
TextBox Manipulation
Background Worker
Copy & Paste
part II transforms &
animations
12 Silly Eye 301
Animation
Event Triggers
Named Resources
Settings Page
Color Picker
Clipping
13 Metronome 327
2D Transforms
Animating Rotation
Animation Completed Event
Frame Rate Counter
Table of Contents
vii
www.it-ebooks.info
part IV pivot, panorama, charts,
& graphs
26 TODO List 611
Pivot
Context Menu
Data Contract Attributes
27 Groceries 649
Panorama
28 Alphabet Flashcards 675

Filmstrip-Style Swiping
29 Weight Tracker 681
Charts & Graphs
part V audio & video
30 Cowbell 711
Playing Sound Effects
Composition Target’s Rendering
Event
31 Trombone 719
Sound Manipulation
Sound Looping
SoundEffectInstance
32 Local FM Radio 731
Radio Tuner
The
NetworkInterface.InterfaceType
Property
33 Subservient Cat 743
Playing Video
MediaElement
part III storing & retrieving
local data
20 Alarm Clock 463
Isolated Storage
Settings
Settings Page Guidelines
Toggle Switch
Using Custom Fonts
Runs
21 Passwords & Secrets 493

Encryption & Decryption
Password Box
Value Converters
DateTimeOffset
Observable Collections
INotifyPropertyChanged
22 Notepad 527
Reading & Writing Files
23 Baby Milestones 545
Reading & Writing Pictures
Serialization
Two-Way Data Binding
24 Baby Name Eliminator 565
Local Databases
Shipping Data with Your App
25 Book Reader 587
Pagination
List Picker
Stretching List Box Items
Table of Contents
viii
www.it-ebooks.info
41 Deep Zoom Viewer 897
Pinch & Stretch Zooming Gestures
Double-Tap Gesture
MultiScaleImage
42 Jigsaw Puzzle 913
Drag Gesture
Image Cropping
WriteableBitmap

Taking Phone Screenshots
43 Spin the Bottle! 945
Rotate Gesture
Simulating Inertia
part VIII accelerometer tricks
44 Boxing Glove 951
Accelerometer Basics
45 Coin Toss 965
Throwing Detection
46 Noise Maker 981
Shaking Detection
47 Moo Can 993
Turning-Over Detection
AccelerometerHelper
Data Smoothing
Accelerometer Calibration
48 Level 1007
Determining the Phone’s Angle
49 Balance Test 1019
2D Motion
50 Pedometer 1035
Analyzing Walking Motion
part VI microphone
34 Bubble Blower 759
Sound Detection
Reversing a Slider
35 Talking Parrot 775
Microphone Audio Playback
36 Sound Recorder 797
Saving Audio Files

Playing Sound Backwards
Multi-Selection List Box
part VII touch & multi-touch
37 Reflex Test 827
The Touch.FrameReported Event
Touch Points
38 Musical Robot 839
Multi-Touch
Tracking Individual Fingers
39 Paint 847
Ink Presenter
Manual Serialization and
Deserialization
XmlSerializer
DataContractSerializer
DataContractJsonSerializer
Undo & Redo
40 Darts 875
Gesture Listener
Manipulation Events
Flick Gesture
Direct Hit Testing
Table of Contents
ix
www.it-ebooks.info
part IX appendices
A Lessons Index 1049
B XAML Reference 1059
CTheme Resources
Reference 1073

D Animation Easing
Reference 1083
E Geometry Reference 1089
Index 1097
Table of Contents
x
www.it-ebooks.info
About the Author
Adam Nathan is a principal software development engineer for Microsoft, a best-selling
technical author, and arguably the most prolific developer for Windows Phone. Adam
previously cofounded Popfly, Microsoft’s first product built on Silverlight, named one of
the 25 most innovative products of 2007 by PCWorld magazine. He is also the founder of
PINVOKE.NET, the online resource for .NET developers who need to access Win32.
Adam has created several top apps in the Windows Phone Marketplace that have been
featured on Lifehacker, Gizmodo, ZDNet, ParentMap, and various Windows Phone enthu-
siast sites. Many of them are identical to or based on apps in this book. Chapter 36’s
Sound Recorder app was featured on MSDN’s first Channel 9 “Hot Apps” show. With the
purchase of this book, the same app is now yours to tweak and sell!
Adam’s books have been considered required reading by many inside Microsoft and
throughout the industry. Adam is the author of Silverlight 1.0 Unleashed (Sams, 2008),
WPF Unleashed (Sams, 2006), WPF 4 Unleashed (Sams, 2010), and .NET and COM: The
Complete Interoperability Guide (Sams, 2002); a coauthor of ASP.NET: Tips, Tutorials, and
Code (Sams, 2001); and a contributor to books including .NET Framework Standard Library
Annotated Reference, Volume 2 (Addison-Wesley, 2005), and Windows Developer Power Tools
(O’Reilly, 2006). You can find Adam online at www.adamnathan.net or @adamnathan on
Twitter.
www.it-ebooks.info
Dedication
To Lindsay, Tyler, and Ryan.
www.it-ebooks.info

Acknowledgments
Behind most authors is either an incredibly understanding spouse or, perhaps more likely,
an ex-spouse. I’m fortunate to say that I’ve still got the former. My wonderful and beauti-
ful wife, Lindsay Nathan, has not only been inhumanly patient and understanding
during the whole book-writing process, but she’s practically my coauthor in this book
series. She came up with many of the app ideas, read significant portions of the book
(despite having no previous programming experience!), found many errors, and suggested
tremendous improvements to the book as well as the apps.
Lindsay constantly surprises me—and everyone around her—with her incredible talent
and ability to excel at absolutely anything she tries. As a result of her involvement, she
has even become a registered Windows Phone developer! You can search for “Lindsay
Nathan” in the Windows Phone Marketplace to see some of her handiwork.
While I was preoccupied with writing for far too long, Lindsay made sure that our life
didn’t fall apart. More than that, she even enabled things to run smoothly. She’s an
incredible mother, wife, and friend and has made more sacrifices for her family than
she’ll ever get credit for. I literally could never have done this or any other book without
her. You, the reader, may have gotten 101 apps out of this book series, but Lindsay has
given me 101 new reasons to love her as much as I do. Thank you, Lindsay.
Although Lindsay is the reason this book is in your hands, this book also came together
because of the work of several talented and hard-working people who aren’t married to
me. I’d like to take a moment to thank them as well, with the risk of accidentally omit-
ting some people.
I owe huge thanks to Dave Relyea, the development lead for the Silverlight for Windows
Phone team and the most knowledgeable Silverlight developer on the planet, for being a
truly fantastic technical editor. Dave actually learned C# when writing the forensic DNA
analysis software used to identify the 9/11 World Trade Center attack victims. After that,
he started working for Microsoft on WPF 3.0, then Silverlight versions 1–4, and then the
Silverlight for Windows Phone Toolkit, before becoming the lead for Silverlight for
Windows Phone. He personally developed many of Silverlight’s (and the toolkit’s) features
described in this book, so having his insight captured in these pages is invaluable.

Dave’s feedback on my drafts was so thorough, the book is far better because of him. He
also did a fantastic job tracking down the right experts to answer questions or add more
depth to a number of topics. As a result, many of the topics covered in this book have
been reviewed by the developer who implemented the corresponding features. Having
that level of scrutiny is priceless. Dave was the technical editor for my first Silverlight
book which, at 250 pages, was much less of a time commitment than editing this book!
I’m grateful he agreed to devote so much time to this book to make me look better and
make you more successful. I hope he’s still up for reviewing Volume II!
I thank Jeff Wilcox, David Anson, Andi Fein, and Austin Lamb, who each did an excellent
job reviewing a chapter. I also thank Peter Torr, Stefan Wick, Joao Guberman Raza, Ashu
Tatake, Shane Guillet, and Edward Sumanaseni for their assistance. I really appreciate it.
www.it-ebooks.info
Matt Cavallari deserves many thanks for his tremendous and timely help. If it weren’t for
his assistance during the early days, this book would probably have been released much
later.
I’d like to thank Tim Rice, James Lissiak, Ben Anderson, Patrick Wong, Andy Sterland, Tim
Wagner, Emily Basalik, Anjali Acharya, Chris Brumme, Eric Rudder, Brandon Watson,
Jason Zander, Gus Perez, and Paramesh Vaidyanathan, who helped in a number of ways.
As always, I thank my family for having the foresight to introduce me to Basic program-
ming on our IBM PCjr when I was in elementary school.
I sincerely thank the folks at Sams, especially Neil Rowe, Betsy Harris, and Gary Adair,
who are always a pleasure to work with. I couldn’t have asked for a better publishing
team. Perhaps against their better judgment, they gave me complete freedom to run with
my crazy idea of a two-part book series on 101 apps. They even enabled me to customize
the design of the books inside and out, which was a lot of fun. They have never
complained about my insistence on full-color printing or numerous nit-picky requests.
Amazingly, with all the pressures publishers face, they didn’t even rush me. This benefits
you greatly in terms of quality and the coverage of developments after the launch of
Windows Phone 7, so please thank them as well. I hope the risks that they’ve taken on
these books work out for them as much as I hope it works out for me.

Finally, I thank you for picking up a copy of this book! I don’t think you’ll regret it!
Acknowledgments
xiv
www.it-ebooks.info
We Want to Hear from You!
As the reader of this book, you are our most important critic and commentator. We value
your opinion and want to know what we’re doing right, what we could do better, what
areas you’d like to see us publish in, and any other words of wisdom you’re willing to
pass our way.
You can email or write me directly to let me know what you did or didn’t like about this
book—as well as what we can do to make our books stronger.
Please note that I cannot help you with technical problems related to the topic of this book, and
that due to the high volume of mail I receive, I might not be able to reply to every message.
When you write, please be sure to include this book’s title and author as well as your
name and phone or email address. I will carefully review your comments and share them
with the author and editors who worked on the book.
E-mail:
Mail: Neil Rowe
Executive Editor
Sams Publishing
800 East 96th Street
Indianapolis, IN 46240 USA
Reader Services
Visit our website and register this book at informit.com/register for convenient access to
any updates, downloads, or errata that might be available for this book.
www.it-ebooks.info
This page intentionally left blank
www.it-ebooks.info
introduction
Many people dream about making millions by selling

smartphone apps. Some people have even succeeded. Sure,
as Scott Adams so humorously points out, earning millions
from apps is a long shot. But with a little creativity, artistic
skill, and programming skill, could you earn thousands?
You bet. Do I think you, as a reader of this book, should be
able to earn more than you paid for it? I do (although I
make no guarantees)!
All kidding aside, there has never been a better time for
hobbyist programmers to make good money doing what
they love. I remember releasing a few shareware games in
junior high school and asking for $5 donations to be sent
to my home address. I earned $15. One of the three dona-
tions was from my grandmother, who didn’t even own a
computer! These days, however, adults and kids alike can
make money on simple apps and games without relying on
kind and generous individuals going to the trouble of
mailing a check! The painless distribution and automatic
payment systems enabled by app stores and marketplaces
is the best thing to happen to developers in a really long
time.
As a new platform at the time of this writing, Windows
Phone 7 is in a unique spot of having a rapidly growing
user base (expected to accelerate with the addition of
Nokia Windows Phones) yet a relatively small number of
Who Should Read This
Book?
Choosing a Technology
Software Requirements
Hardware Requirements
Code Examples

How This Book Is
Organized
Conventions Used in
This Book
www.it-ebooks.info
developers. Your apps have a pretty good chance of standing out in the still-young
Windows Phone Marketplace.
So let’s get started building some apps! I’ve been writing programming books for a long
time, but I’ve never been more excited about the topic than I am for Windows Phone 7. I
feel that it deserves a different kind of treatment unlike any I’ve seen. This book is not
just app-focused, but focused on the things that really matter when building apps.
I wrote this book with the following goals in mind:
➔ To be insanely practical, with examples that you can credibly ship as complete apps
➔ To provide a solid grounding in the underlying concepts in an approachable fashion
➔ To answer the questions most people have when learning Windows Phone develop-
ment and to show how commonly desired tasks are accomplished
➔ To be an authoritative source, thanks to input from many members of the Windows
Phone team who designed, implemented, and tested the technology
➔ To help you write apps that look great and follow Windows Phone design guidelines
➔ To help you follow best practices but not shy away from hacks if they’re needed to
get the job done
➔ To not limit the book to the functionality that ships with Windows Phone, but to
also include interesting open source libraries
➔ To optimize for concise, easy-to-understand code rather than enforcing architectural
patterns that can be impractical or increase the number of concepts to understand
➔ To be fun to read!
To elaborate on the second-to-last point: You won’t find examples of patterns such as
Model-View-ViewModel (MVVM) in this book. I am a fan of applying such patterns to
code, but I don’t want to distract from the core lessons in each chapter. You are certainly
free to apply such patterns as you make changes to these apps for your own needs,

although I personally find that it can be overkill given the limited size and scope of some
apps.
Who Should Read This Book?
This book is for software developers of all skill levels who want to write apps for Windows
Phone. It is certainly not just a book for beginners; even developers who are Silverlight
pros and/or Windows Phone pros should be able to get a lot out of it.
This book does not teach you how to program, nor does it teach the basics of the C#
language. However, it is designed to be understandable even for folks who are new to the
.NET Framework and does not require previous experience with Silverlight or with
Windows Phone.
Introduction
2
www.it-ebooks.info
As my wife will attest, even nonprogrammers can follow along to some degree and tweak
the apps in this book. If you’ve got a knack for graphic design and you have some good
ideas for ways to re-theme the apps in this book, you could be quite successful in the
Windows Phone Marketplace!
Choosing a Technology
3
If you’re thinking about tweaking some apps in this book and wondering how to get the
most bang for your buck, you might consider searching for “Adam Nathan”in the Windows
Phone Marketplace (or visiting ) to examine the relative popu-
larity of this book’s apps. Although I’ve enhanced some of my apps in the marketplace compared
to what is in this book, many of them are identical.
I’m really interested to see what apps you publish based on apps in this book! Send me a
tweet with details, and I might highlight your apps. I’m @adamnathan on Twitter.
Choosing a Technology
Windows Phone supports two primary programming models: Silverlight and XNA.
Silverlight, originally designed as a plugin for Web browsers, enables the rapid develop-
ment of rich applications. It emphasizes declarative UI with powerful support for anima-

tion, data binding, vector graphics, and controls that can be easily composed and
themed. The current version of Silverlight used by Windows Phone is effectively the same
as version 3 used by Windows and Mac, but with some irrelevant features removed and
other phone-specific features and performance tuning added.
XNA, originally designed for Xbox but also available for Windows and Zune HD (as well
as Windows Phone), enables high-performance games, whether 2D sprite-based games or
games with full 3D graphics. Windows
Phone supports the same XNA 4.0 Reach
profile that is supported on Xbox and
just about all modern PCs, except it does
not support shaders.
The typical advice for developers is, “Use Silverlight for apps and XNA for games.” The
reality is a little more subtle.
Building Games with Silverlight
You can certainly create fantastic games with Silverlight, as games are apps, too! Chapter
40, “Darts,” is a great example of this. Shortly after I released a version of this app in the
Windows Phone Marketplace, it was ranked as the #11 paid app, sitting among many
Xbox LIVE games that use XNA. Games written in Silverlight have several advantages at
the time of this writing, such as easy integration with services such as Facebook and
Twitter, as well as the ability to use all the standard Silverlight controls (perhaps re-
themed) for menus, scoreboards, and more.
XNA Does Not Stand for Anything
However, it is commonly stated that it’s actu-
ally an acronym for “XNA is Not an Acronym.”
www.it-ebooks.info
On the other hand, trying to create complex games with Silverlight can be infeasible
performance-wise. 3D games are also out of the question. Xbox LIVE features are only
available for XNA games, but you need to be a specially designated Xbox LIVE developer
to take advantage of these features anyway.
Building Apps with XNA

You could write a nongame app with XNA, but that would be a strange thing to do.
Besides being a lot more work to re-create basic controls such as buttons and list boxes,
XNA apps are not currently able to take advantage of the user’s phone theme, the applica-
tion bar, the web browser control, and more. Several third-party control libraries exist for
XNA, however, that can make your job much easier. See and
/>Mixing Silverlight with XNA
An app can mix and match functionality
from Silverlight and XNA. Although all
50 apps in this book are Silverlight apps,
several take advantage of XNA function-
ality: using the microphone, playing
sound effects, and so on. And although
XNA apps cannot embed a web browser,
they can use Silverlight’s networking
classes to make web requests. The only
limitation is that, at the time of this
writing, you cannot mix Silverlight user
interface rendering with XNA user inter-
face rendering. From the perspective of
the user interface, an app can only be one or the other.
The relationship between Silverlight and XNA is more confusing than it needs to be,
caused by the goal of Silverlight for Windows Phone to be mostly compatible with
Silverlight for Windows and Mac, and by the goal of XNA for Windows Phone to be
mostly compatible with XNA for Xbox, Windows, and Zune HD. The result is some dupli-
cation of functionality and arbitrary distinctions between technologies. For example,
although Windows Phone has a single class for interacting with the microphone, it is an
XNA feature (and lives in an XNA assembly) simply because it’s compatible with what
earlier versions of XNA have already exposed to developers.
HTML, CSS, and JavaScript
A final subtlety is that there’s really a third development model you can use for Windows

Phone apps: the combination of HTML, CSS, and JavaScript. Technically, such an app
would be a Silverlight app that hosts the web browser control, but inside that control you
could provide an entire app’s experience with HTML, CSS, and JavaScript that is either
Introduction
4
Marketplace certification
enforces that Silverlight and XNA
are not improperly mixed!
Even if you find some way of using XNA user
interface pieces in a Silverlight app that
seems to work, your app will not be approved
for inclusion in the Windows Phone
Marketplace at the time of this writing. As
long as you avoid referencing
Microsoft.Xna.Framework.Game.dll and
Microsoft.Xna.Framework.Graphics.dll
in a Silverlight app, you should be fine.
www.it-ebooks.info
locally hosted or resides on a Web server. With a little bit of C# glue code in the app
hosting the web browser, you could even cause pieces of your HTML user interface to
trigger phone-specific actions, such as initiating a phone call.
Software Requirements
5
Can I write an app with HTML5 for Windows Phone?
Not at the time of this writing, but you will be able to by the end of 2011. Microsoft has
announced that Internet Explorer 9 will be available on Windows Phone by this time.This not
only adds great HTML5 support to the Internet Explorer app, but to the web browser control
available to developers as well.
Can I write a game for Windows Phone with OpenGL?
No.Your best bet is to use XNA.

Software Requirements
This book targets Windows Phone 7 (all phone models running Windows Phone OS 7.0)
and the corresponding Windows Phone Developer Tools.
Other than the desktop operating system you use for development (which can be
Windows Vista or later, but not Windows Server), getting the most out of this book
doesn’t require anything other than free software:
➔ The Windows Phone Developer Tools, a free download at
, includes
➔ Visual Studio 2010 Express for Windows Phone, used for developing Silverlight
apps
➔ Expression Blend 4 for Windows Phone, which can optionally be used for
designing Silverlight-based vector graphics, animations, and control templates
➔ XNA Game Studio 4.0, used for developing XNA apps
➔ Windows Phone Emulator, used for running and testing your apps on a PC
rather than a real phone
This book has been tested with the January 2011 update of the tools, which adds
copy/paste support to the emulator’s version of the Windows Phone operating
system (version 7.0.7338.0).
➔ The Silverlight for Windows Phone Toolkit, a free download at
, which contains numerous controls and important
features missing from the Windows Developer Power Tools. This book has been
tested with the February 2011 version. Later versions are not guaranteed to be back-
wards compatible, so be careful if you decide to try a later version.
www.it-ebooks.info
➔ The Silverlight Toolkit, a free download also available at
, which contains additional controls that can be used
on Windows Phone, such as charts and graphs.
➔ PAINT.NET, a free download at , used for creating and editing
graphics.
Throughout the book, links to other resources are given as they are needed.

If you already use a more powerful edition of Visual Studio, you don’t have to use the
Express edition included in the Windows Developer Power Tools; installing the tools also
adds the Windows Phone-specific functionality to other editions. Any differences between
Visual Studio Express and paid editions of Visual Studio have nothing to do with
Windows Phone; the differences are in developer productivity features, application lifecy-
cle management tools, and so on.
The current version of the Windows Phone Developer Tools, and this book, only supports
programming with C# and XAML. However, you can download an extension to Visual
Studio Professional or higher that enables the use of Visual Basic instead of C# when
creating Silverlight apps for Windows Phone. See
/>If you choose to use Visual Basic instead
of C#, you should still be able to use this
book. After all, the concepts, APIs, and
XAML are identical. The only thing you
miss out on is the ability to directly
copy/paste from the vast amount of
code accompanying this book, at least
without a C#-to-VB conversion tool.
Introduction
6
Although app certification require-
ments for the Windows Phone
Marketplace are discussed throughout
this book, they regularly undergo slight
changes.You can download the latest require-
ments in PDF form at />Several Windows Phone development tools exist that are not free.Two worth mentioning
are
➔ Silverlight Spy ( which enables you to inspect
and tweak your app’s element tree and even inspect its isolated storage contents
➔ Runtime Intelligence for Windows Phone ( />which enables obfuscation, optimizations, and analytics

Hardware Requirements
You’re going to need a computer that can run the software listed in the preceding section.
In addition, although technically not required, I recommend testing any apps you submit
to the Windows Phone Marketplace on a real phone.
www.it-ebooks.info
The emulator that comes with the
Windows Phone Developer Tools is very
good for most things, but there are
many things it doesn’t emulate. For
example:
➔ It doesn’t provide a good way to test accelerometer data.
➔ It doesn’t provide a way to emulate multi-touch gestures unless you
have a multi-touch PC or use techniques such as the one described at
/>➔ You can’t test consuming pictures from the camera, although it does provide some
built-in photos you can use with the photo chooser.
➔ It doesn’t expose full functionality when launching external actions such as
composing an email.
➔ It doesn’t expose the built-in apps, which are handy to examine for matching the
style and conventions expected of Windows Phone apps.
➔ It doesn’t provide a way to test the FM radio tuner.
Hardware Requirements
7
As a developer, what phone should I purchase for testing my apps?
The beauty of Windows Phone 7 is that it shouldn’t matter. Despite the variety of form
factors, the functionality exposed to developers is consistent. For example, although some
models have better cameras than others, the way you interact with the camera doesn’t know or
care. (The downside of this consistency, of course, is that you cannot write an app that takes
advantage of the unique hardware features of a specific phone, unless you are the manufacturer
of the phone.)
The most obvious difference between phone models is the existence of (and placement of) a

hardware keyboard. Although I did some testing on a model with a hardware keyboard, it was no
longer necessary once I learned how it worked. And I share that information with you in Chapter
3,“In Case of Emergency.” So don’t feel that you need to buy a phone with a hardware keyboard
solely for testing purposes! The emulator also does a good job of emulating a portrait slide-out
hardware keyboard.
As time goes on and phones become increasingly differentiated by processing power, testing
your apps on the least powerful phone could become interesting for ensuring they run quickly
enough.
Although the screen resolution (480x800 pixels) is common among all Windows Phone 7 phones,
the physical size of the screen may vary slightly. Keep this in mind for anything that relies on
physical measurements (as with the Ruler app in Chapter 5).The solution for this is to ensure that
you provide calibration so the user can adjust your app to their device accordingly. All the apps in
this book were tested on a Samsung Focus.
You can purchase a Windows phone
without a voice or data contract
at />windowsphonedeveloperpurchase.
www.it-ebooks.info
For me, running apps on a phone is helpful for ensuring that touch targets are not too
small, too close together, or too close to
the edge of the screen. When I created a
pool game, I didn’t realize that the user’s
finger would block important informa-
tion on the screen until I tested it on a
real phone. The bottom line is that
submitting apps to the Windows Phone
Marketplace that you’ve only tested on
the emulator is risky.
Introduction
8
With the emulator, you can’t predict the performance of your application

when it runs on a physical device!
Sometimes an app runs faster on the emulator and sometimes it can actually run more slowly,
based on a number of factors. Although you certainly use it to test relative performance improve-
ments you make, there is absolutely no substitute for running it on a real phone.
That said, if you try to gauge performance while running in the emulator with frame rate counters
enabled (see Chapter 13,“Metronome”), the fill rate value is the best predictor of device rendering
performance.
When using the emulator during devel-
opment, keep it open! You don’t need to
close the emulator every time you
change and redeploy your app. And you
shouldn’t, because it can be quite slow to start
up. By keeping it open, you can redeploy your
app and start additional testing in about 1–2
seconds.
For the most part, using the emulator is straightforward, but there are a few keyboard
shortcuts that are good to know about:
➔ The F1 key is a keyboard shortcut for the hardware Back button.
➔ The F2 key (or Windows key) is a keyboard shortcut for the hardware Home button.
➔ The Pause key toggles the hardware keyboard.When it is activated, you can type with
your computer’s keyboard rather than clicking keys on the screen (which can be excruci-
ating).You can also use Page Up to enable the hardware keyboard and Page Down to
switch back to the on-screen keyboard.
The emulator has many other keyboard shortcuts, most of which aren’t supported by the limited
version of the Windows Phone operating system that currently ships with the emulator. See
for more details.
Code Examples
The source code for examples in this book can be downloaded from
www.informit.com/title/9780672335525. You must register your book before you can
access the source code.

How This Book Is Organized
This unconventional book contains 50 chapters, one for each complete app in the avail-
able source code. Although each chapter is focused on building a specific app, the goal of
www.it-ebooks.info

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×