WP7 Teach-In recap

On Thursday night the Atlanta Leading Edge user group hosted a Teach-In for Windows Phone in which we got 15 people relatively new to phone development to build two common phone apps in about 90 minutes.

There was a lot of discussion about the ins-and-outs of the developer tools as well as strategies for the sorts of apps that people are working on.

Mostly, however, the meeting was simply about getting our hands dirty and seeing how easy it is to build phone apps using Silverllight.

The apps were trivial.  First, we built an app that played a wav file using the XNA libraries from a Silverlight app.  Everyone downloaded a sound file from  the Internet and in 15 minutes we had meowing cats, breaking glass, screeching cars and hysterical laughing playing from each laptop in the room.  This simple technique is the basis for a remarkable number of apps on the iPhone and Android phones.

Next we all built a Twitter application.  Again, it is a trivial task, to use the WebClient class in Silverlight.  By doing this, we demonstrated another essential technique for building phone apps – remote communication with web resources.

I’ve participated in several conversations about the best way to teach Windows Phone development.  Our little experiment demonstrated that learning-by-doing works particularly well in this case. The hardest part of teaching any new technology is getting people over the hurdle of being intimidated by it.  Once people realize that they have already done something they thought was difficult, the anxiety goes away and they can start thinking about what they want to do with a technology rather than how they are going to get started.

WP7 and the Anxiety of Influence

iphone wp7

When Microsoft put together a design team over a year ago to come up with “Metro” – the design language for their new Windows Phone platform – they were faced with a difficult challenge.  After years of ignoring Apple’s iPhone and trying to heap features onto the Windows Mobile platform in an effort to compensate for a lack of  design savvy – to the extent that even owning a Windows Phone was considered a career limiting move for Microsoft employees – a sudden change of direction occurred within Microsoft.  All at once, design values seemed to matter.

But what should the new phone look like?  Led by people like Albert Shum from Nike, the new design team could not afford to ignore the iPhone.  Ignoring the iPhone was in part the source of Microsoft’s decline in the phone market up to that point.  They also could not simply copy the iPhone’s look.  An iPhone knock-off would quickly kill the venture.   Finally, they faced the danger of trying too hard to design an anti-iPhone.  This would be just as deadly as creating something that looked too much like the iPhone.

The literary critic Harold Bloom coined the term “anxiety of influence” to describe a similar problem that faced the great Romantic poets.  Byron and Keats learned to be poets by reading and emulating John Milton.  At some point, however, they had to find their own voices in order to become great poets in their own right.  What greater horror can there be for a poet that leaving of the footsteps of a greater poet and making a new path.  The tracks of the master are sure while the new steps are difficult to evaluate – are they brilliant but different or merely random steps that eventually end in the gutter?  What must Shakespeare have felt as he stepped from behind the shadow of Christopher Marlowe and first tried to pen something original and truly Shakespearean?

As the release date for Windows Phone approaches – as developers wait for the WP7 Marketplace to start accepting applications – phone developers must decide what sort of apps they will build for the device.  Will they copy the great apps of the iPhone – the fart app, the beer app, the squealing cats app – or will they come up with something original?

Writing a phone application is not quite the same thing as writing poetry.  The goal of the one is to create art that edifies and glorifies while the goal of the other is to make money.  So everyone should definitely take some time to write a copy of an Android app that is a copy of an iPhone app that was a bad idea in the first place.

But what do we do after that?

Phone apps are a genre unto themselves.  They have to work within a small display.  Ideally they should be simple.  They must be easy to use since users of phone apps have short attention spans.  Yet people continue to copy ideas that are native to to PCs and game consoles.  It is worth emphasizing that a phone is not a light-weight PC and it certainly is not a light-weight console (that’s what the Nintendo DS is for).

Is it talking in circles to say that the apps we write for the phone should be guided by a notion of what works well on the phone and nowhere else?  To paraphrase Bill Buxton, any idea is good for something and terrible for something else.  For this reason, with the phone we should be wary of ideas that work well on other platforms.  If they work best on other platforms then there’s no need for them on the phone.  The real breakthroughs will be with game concepts that are horrible for the PC or the game console – or even for the iPhone – but which might just work great on Windows Phone 7.

And then there are the ideas no one has thought of yet.

To that end, here are links to some rather crazy, idiosyncratic games.  They may simply be frustrating or, potentially, they could be inspiring.  Here is an article from the New York Times to accompany them.

Erik Svedang’s Blueberry Garden

Cloud by Jenova Chen and Kellee Santiago

Jason Rohrer’s Passage

The WP7 design team in the end were able to overcome the anxiety of influence by setting up a manifesto, of sorts, outlining their design philosophy and building up from there.  Where the iPhone design philosophy is dominated by icons and gel buttons, the WP7 core philosophy, called Metro, is built around text and flat, “chrome-less” design.  The overwhelming spirit is one of minimalism.  The Metro design even has precedents in the Bauhaus movement and the works of Frank Lloyd Wright – a return to simplicity in design and an eschewing of ornamentation without purpose.  At times, the Black Book even reads like Adolf Loos’s famous 1908 essay Ornament and Crime.

How to find a Silverlight Expert

Despite being available for several years now in different forms, Silverlight is still a technology that few developers are experienced in using.  Not many companies have roles for fulltime Silverlight developers, which limits the opportunities for developers to become proficient in using it.

On the other side, when a company has need of a Silverlight developer they want someone with a lot of experience.

This makes finding a Silverlight developer very difficult.  Contrarily, it makes being a Silverlight expert very rewarding.

An additional complexity is that there are different kinds of Silverlight experts.  Some are Line-of-Business Silverlight developers.  They are primarily concerned with questions such as whether to use REST, WCF SOAP services or RIA Services in order to retrieve data.  They compare the advantages and disadvantages of using MEF versus Prism.  They spend their free-time developing better MVVM frameworks and they spend most of their development time with Visual Studio open.

Integrators are a different breed of Silverlight expert.  They spend most of their time in Expression Blend and are concerned with how a Silverlight application looks.  This is often mistakenly referred to as eye-candy.  It is much more than that.  Integrators are proficient at making a compelling experience.  They devote their energies toward timing animations, making applications usable, and drawing the user into the Silverlight experience.  They are practitioners of subtlety and believe that the best user experience is one the user doesn’t even notice. Getting a Silverlight application to talk to a database is important, but if it looks bad no one is going to use it.  Some Integrators, by the way, also spend their free-time developing better MVVM frameworks.

If you are fortunate, you will find a Silverlight developer who does LOB work as well as Integration.  But you have to know what kind of SL developer you are looking for.

The best place to find a Silverlight expert – besides at Microsoft headquarters in Redmond – is probably Microsoft’s MVP site.  The MVP program is sponsored by Microsoft and recognizes accomplished developers in a variety of specializations.  One of the specializations is Silverlight.  There are currently 52 Silverlight MVPs worldwide.  There are an additional 30 Blend MVPs.

In addition to Blend and Silverlight MVPs, you will find that many Phone, ASP.NET and especially Client App Dev MVPs are also now working in Silverlight fulltime but haven’t shifted their designation.  This is quite a large pool of Silverlight experts to work with and at least a few should be in your region.

And then there are the creme-de-la-creme Silverlight Experts.  Some are independent and some work for companies or consultancies.  They are mostly known by word-of-mouth and no two lists of who are the best Silverlight experts are going to be quite the same.  At the risk of missing a few, here is a non-exhaustive and unordered list of people I consider to be Silverlight gurus:

Shawn Wildermuth, Jeff Prosise, Corey Schuman, Jeff Paries, Rick Barraza, Robby Ingebretson, Erik Mork, Bill Reiss, Justin Angel, Jonas Follesoe, Laurent Bugnion, Adam Kinney, Page Brooks.

I know I’ve forgotten someone important and I apologize in advance.

Among consultancies that specialize in Silverlight work, the three I know the most about are Pixel Lab, Vertigo and Wintellect.

Pixel Lab is simply the all-star team for Silverlight and Windows Phone development with Robby Ingebretson, Kevin Moore and Adam Kinney all working there.

Vertigo is well known for doing high-profile, beautiful Silverlight sites.  They also have a very close relationship with Microsoft.

Wintellect is another boutique consultancy that happens to specialize in Silverlight back-end work.  They are headed up by Jeffrey Richter, Jeff Prosise and John Robbins and tend to hire only the best.

If you are looking for Silverlight training rather than Silverlight development, both Shawn Wildermuth and Erik Mork are excellent trainers who cover the Silverlight field.

Creating an Application Bar in Blend

Ingredients: Windows Phone Dev Tools beta, Expression Blend for Windows Phone

The application bar in Windows Phone 7 is a core visual element in any Silverlight application built for the phone.  The development tools make it very easy to implement an application bar with just a few lines of code. 

xmlns:phoneNavigation="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
>
<phoneNavigation:PhoneApplicationPage.ApplicationBar>
    <shell:ApplicationBar>
        <shell:ApplicationBarIconButton Text="delete"  
                IconUri="/Icons/appbar.delete.rest.png"/>
    </shell:ApplicationBar>
</phoneNavigation:PhoneApplicationPage.ApplicationBar>

This code can also be moved to a page resource or an app resource in case the toolbar is reused.  The toolbar can also be created in code for greater control.

Along with other changes, the new beta of the Windows Phone dev tools now also allows Application Bars to be created in Blend for Windows Phone.

appbar

For those moving from the CTP to the Beta tools, you will find that there are some new improvements as well as some of the earlier limitations.

The Application Bar, as previously, has very slick transitions built-in.  It is a pleasure to work with.

As previously, the properties of an Application Bar cannot be bound (as far as I can tell), so the developer needs to go into code-behind, for the most part, to implement any complex visual logic (or even simple logic like hiding and showing Icon Buttons) as well as to handle click events. 

As previously, the Application Bar must be attached to a PhoneApplicationPage.  You cannot get different app bars to reveal themselves by attaching them to user controls.  If you have logic that requires this (for instance if you want different app bars to be used for different panels of a Hub) you will need to track the state of the hub and hide and show the appropriate Application Bar manually in the hosting PhoneApplicationPage’s code-behind.

As for the new, ApplicationBarIconButtons now take a Text property (and in fact are required to have non-empty Text).  When a user selects the ellipses at the upper right of the application bar, the text will appear (in the picture above, taken from the One Note application, the text is “email”).

And, as I mentioned, the Windows Phone app bar is now Blendable.

if you open up a new project in Blend for Windows Phone and select a page, you’ll notice a new element representing the ApplicationBar in the Objects panel.

oandt

This is a property that takes an IApplicationBar object (that it takes an interface suggests that we can extend the base implementation of the ApplicationBar – though I have yet to find a good case for doing so).

In order to add an application bar to our page, select the PhoneApplicationPage element in Objects and Timeline.  Now go to the Properties panel at the upper left of the Blend IDE and look for the Common Properties tab (alternatively, search for “ApplicationBar”).

commonproperties 

A new ApplicationBar can be created for the page by selecting “New”.

appbartab

Here things get a little funky.  I assume the features are still being added for the app bar – though there’s always the possibility that I have something wrong with my install.  The BackgroundColor and ForegroundColor never seem to change in the display of the Properties panel (though they do change in the XAML).  Also, if you select either the Buttons or MenuItems collection, you are thrown into a bit of confusion.  The following images show the steps for adding an icon button.

The screen after this shows a standard dialog box for a list.  You can select “add another item” from this dialog.

The “add another item” dialog, however, is messy. 

selecticonbutton 

Lots of classes besides ApplicationBarIconButton or ApplicationBarMenuItem show up even though these are the only two types you can actually add to an ApplicationBar.  This will undoubtedly get fixed within the next few months.  Search for ApplicationBarIconButton and select it to add an icon button to the app bar.

You will be returned to the buttons collection editor where you must now set two properties of an ApplicationBarIconButton: Text and IconUri.  (IsEnabled defaults to “true” if you leave it alone.)

iconbutton

One of the very cool features here is that the dropdown box next to IconUri allows you to select from a list of standard Icons used in WP7.  When you select one of these, the IDE automatically goes out and copies the selected icon into a newly created “icons” folder under your project.

Not to belabor my war stories, but back in the day (I’m talking about last week) we used to have to download all the images from the web and then add them to our projects manually.  That may seem like no big deal, but there were actually two different sets of icons – one for the dark theme, which were white on black, and one for the light them, which were black on white.  Worse, there was no obvious way to find the theme currently being used, so we would check the background color of the app, in code, to determine whether it looked like the dark or the light them was being used.  Then we would programmatically switch out the icons based on what the background color happened to be.  But at least we had character back then and understood the value of a hard day’s work.

So now not only is all of that easier with the beta SDK, but you also get a designer preview of what your app bar looks like.

appbarpreview

But wait … there’s more.  If you go to the upper right docking panel in the standard layout, there is now a “Device” tab that allows you to preview how your app will look under different themes.

devicepanel

If you select the Light device, the app bar shown above will now look like this.

lighttheme

Your project, however, still only has the original image you added when you selected a value for the IconUri property of the app bar icon button.

oneicon

We no longer have to manage multiple images for the same icon button.  WP7 is apparently manipulating the one physical image in order to accommodate the current theme on the device.

This technique for image management allows for an interesting additional feature.  You will recall from above that the application bar has a foreground property.  If I set this to red, Blend actually freaks out and doesn’t show the app bar anymore.  If I run the app in the emulator, however, I get this and this:

rediconbutton redongray

Setting the background property, in turn, only affects the “clicked on” image.  When you click on an icon button, the foreground color becomes the background color for the image and the specified background color becomes the foreground color.  When the icon is not clicked, it still looks as it does above.  It’s a little confusing, but still a very cool effect.

Like most controls in Blend, once you finish defining your ApplicationBar, you can convert it into a resource.  Select the difficult-to-see little white square next to the “New” button to open up a dialog that will walk you through making the app bar a page or an application resource.

resourceit

createIApplicationBar

This will change the XAML in your page to this:

    <phone:PhoneApplicationPage.ApplicationBar>
        <StaticResource ResourceKey="MyApplicationBar"/>
    </phone:PhoneApplicationPage.ApplicationBar>

while the actual implementation of the ApplicationBar will be in your App Resources.

Summary

The improvements to the ApplicationBar have been incremental but are very much welcome.  Once all the bugs have been worked out, Blend’s support for the ApplicationBar will be useful.  I still wish we could bind the ApplicationBar properties.  Considering how much we get for free, however – standard icon images, snazy transitions – there’s really not much to complain about and lots to be grateful for.  The Windows Phone implementation of the ApplicationBar makes it easy to implement and attractive and common user interface for performing simple tasks.

Uninstalling Windows Phone CTP Dev Tools

The new beta tools for Windows Phone have just come out.  If you haven’t previously downloaded the April CTP Tools, you are in great shape.  Just download from the link above and you should be good to go.

If you have previously installed the CTP, however, there is some uninstalling to do first.  Moreover, a peculiarity of the CTP was that it worked only with the Blend 4 CTP and did not work with the Blend 4 RTM.  This entails that you will also want to uninstall the Blend 4 CTP if you have been holding out all this time.

The Blend / WP7 story has also gotten more interesting.  The dev tools linked above include an edition of Blend called Blend for Windows Phone beta (sort of the equivalent of Visual Studio Express).

If you have a subscription to MSDN, you now need an Ultimate subscription to get Blend 4 (as part of the Expression Studio Ultimate).  Blend 3 used to be available with the Premium subscription but, alas, no longer.  You can get the Expression 4 Studio Trial here.

However, the new developer tools do not work with Expression Blend 4.  They only work with Blend for Windows Phone beta.  But at least now you can use the Blend 4 RTM for your other Silverlight and WPF projects.

Uninstall

Assuming you have the Blend 4 RC and the April CTP Refresh of the Windows Phone dev tools, you will want to uninstall the following:

  • Microsoft Expression Blend 4 CTP
  • Microsoft Windows Phone Developer tools ENU

[Reboot your OS]

  • Microsoft Expression Blend 4 Add-in Preview 2 for Windows Phone
  • Expression Blend SDK RC for Silverlight 4
  • Expression Blend SDK RC for .NET 4

That seemed to do it for me.  In the process several other Phone related components were automatically uninstalled including:

  • Microsoft Windows Phone Developer Resources
  • Microsoft XNA Game Studio 4.0 Windows Phone Extensions
  • Windows Phone Emulator x64 – ENU

Reinstall

From here I

  • installed the RTM for Blend 4 (just so I can use it for Silverlight 4 projects). 
  • installed the Windows Phone Developer Tools beta.

What’s Changed

1. First of all, the emulator has a new look.  It seems a little smaller to me.  It also has a flatter look, and the black has been replaced with a gray/silver chrome.

newEmulator

2. If you were using an unlocked ROM for your development, you are back to the regular unlocked ROM until the XDE gurus get around to unlocking the new one.  You can read this XDE forum thread to learn more.

3. Blend 4 RTM appears to be useless for phone development.  You will need to use the Blend for Windows Phone beta for your integration and animation work.  I tried, of course, to open a project built in “Blend Express” with Blend 4 RTM, but got a message that I didn’t have the correct version of the WP7 Tools installed.

4. On the flip side, Visual Studio (Premium or Ultimate) now allows you to add service references.  Previously you had add references in Visual Studio 2010 Express and then copy them into your VS 2010 project.  This is much nicer.

5. Third party templates are now broken.  I’ve been using Laurent Bugnion’s MVVM templates and now understand why he has been putting off upgrading them. 

6. All your current phone apps will need to be fixed because they will be broken.  The Windows Phone team moved lots of assemblies around and reorganized namespaces.  You’ll need to go through your apps and fix your assembly references as well as the namespaces in XAML as well as in your code.  Jaime Rodriguez has blogged on the steps necessary to repair your apps.  His blog is currently getting slammed – so if you can’t get through, just keep trying. 

WP7 InputScope

qwerty

In Windows Phone development, InputScope is a property that can be attached to a TextBox control.  It is also one of the most convenient features of Silverlight for Windows Phone.

On a phone device, we cannot depend on having a keyboard to enter text in our applications.  The InputScope attached property provides a way to automatically associate a digital touch-aware keyboard to textboxes in our application.  The syntax, moreover, is extremely simple.  To create a keyboard like that shown above, all you have to do is set a value for the InputScope property like this:

<TextBox Name="myTextBox" InputScope="Text"/>

when the TextBox receives focus, the visual keyboard automatically pops up.  When focus leaves the TextBox, the keyboard will hide itself.  Additionally, the “Text” input scope has predictive text completion built in.  If you begin typing “R-I-G” and the InputScope is set to “Text”, the visual keyboard will make some suggestions on how to complete your word.

qwerty2

I showed the short syntax for the InputScope above.  In the Blend 4 RC, the xaml parser in design mode marks the short syntax as invalid (though it will still compile).  The longer syntax for setting the Input Scope looks like this:

<TextBox x:Name="myTextBox">
    <TextBox.InputScope>
        <InputScope>
            <InputScopeName NameValue="Text"/>
        </InputScope>
    </TextBox.InputScope>
</TextBox>

I am currently still using the Windows Phone April CTP Refresh, in which not all of the Input Scope implementations are complete.  Hopefully in the next drop I will be able to show more examples of the various Input Scope keyboard designs.

Using the long syntax above will allow intellisense support to provide a listing of all the input scope values that can be entered for the InputScopeNameValue.  You list out these values programmatically by using a little reflection (the Enum class in Windows Phone is a bit different than the regular C# enum class, so GetNames isn’t available):

var inputScopes = new List<string>();

FieldInfo[] array = typeof(InputScopeNameValue).GetFields(
        BindingFlags.Public | BindingFlags.Static);
foreach (FieldInfo fi in array)
{
    inputScopes.Add(fi.Name);
}

this.DataContext = inputScopes;

A simple app can be written to try out the different input scope keyboards as they become available.  If you use the code above to set the data context on your page, the following xaml should provide a select list for experimenting with different visual keyboards:

<StackPanel>
            <TextBox x:Name="myTextBox" 
        InputScope="{Binding ElementName=lbInputScopes
    ,Path=SelectedItem}"/>
<ListBox x:Name="lbInputScopes" 
            ItemsSource="{Binding}" 
            Height="500" />
</StackPanel>

Here is the full list of InputScopes that are expected to be supported, based on the current enum names for InputScopeNameValue:

1. AddressCity
2. AddressCountryName
3. AddressCountryShortName
4. AddressStateOrProvince
5. AddressStreet
6. AlphanumericFullWidth
7. AlphanumericHalfWidth
8. ApplicationEnd
9. Bopomofo
10. Chat
11. CurrencyAmount
12. CurrencyAmountAndSymbol
13. CurrencyChinese
14. Date
15. DateDay
16. DateDayName
17. DateMonth
18. DateMonthName
19. DateYear
20. Default
21. Digits
22. EmailNameOrAddress
23. EmailSmtpAddress
24. EmailUserName
25. EnumString
26. FileName
27. FullFilePath
28. Hanja
29. Hiragana
30. KatakanaFullWidth
31. KatakanaHalfWidth
32. LogOnName
33. Maps
34. NameOrPhoneNumber
35. Number
36. NumberFullWidth
37. OneChar
38. Password
39. PersonalFullName
40. PersonalGivenName
41. PersonalMiddleName
42. PersonalNamePrefix
43. PersonalNameSuffix
44. PersonalSurname
45. PhraseList
46. PostalAddress
47. PostalCode
48. Private
49. RegularExpression
50. Search
51. Srgs
52. TelephoneAreaCode
53. TelephoneCountryCode
54. TelephoneLocalNumber
55. TelephoneNumber
56. Text
57. Time
58. TimeHour
59. TimeMinorSec
60. Url
61. Xml
62. Yomi

Navigating around windows phone 7

Vermeer-the-Astronomer

Navigation in Silverlight applications for Windows Phone is simpler, if somewhat more constrained, than in Silverlight applications for the web. 

In classic Silverlight applications the template on which we build our pages is the UserControl.  User controls are set as the root visual for the applications and, at least before Silverlight 3, navigation was typically handled by replacing one user control with another.

Silverlight 3 introduced a special navigation control.  While the root visual for a Silverlight application was still a user control, the user control could host a navigation “Frame”.  The frame, in turn, hosts “pages”, which are just specialized user controls.

Silverlight for Windows Phone adopts the navigation scheme exemplified by the latter set of classes: frames and pages.  It also simplifies it.  Instead of hosting the navigation frame in a page, a specialized class called a PhoneApplicationFrame is the root visual in a WP7 application.  It, in turn, hosts a variety of PhoneApplicationPages.

It is helpful to think of the PhoneApplicationFrame as a web browser.  Like a web browser, it never changes when you move between pages.  Instead it acts as a viewer for the pages you want to navigate between.  You navigate between pages, in turn, simply by passing a uri to the browser.

The PhoneApplicationFrame is typically set in the app.xaml file (though it can also be set programmatically).  The Source attribute of the frame is set to the uri for the initial PhoneApplicationPage.

<Application.RootVisual>
        <phoneNavigation:PhoneApplicationFrame 
        x:Name="RootFrame" 
        Source="/MainPage.xaml"/>
    </Application.RootVisual>

So how do we navigate between different pages in our application? 

1. One way is to simply use a HyperlinkButton control.  The NavigateUri attribute can be set to the location of another PhoneApplicationPage (in this case, the MyView page in the root of my application).  When the user clicks on the link, the root frame will navigate to the new page. 

<HyperlinkButton Content="HyperlinkButton"  
                     Name="MyViewLink"
                     NavigateUri="/MyView.xaml" />

You will want to include the initial slash in your path.  If you don’t, the phone application will open up a mini-browser and attempt to navigate to the specified uri on the web.  For instance, if the NavigateUri above is set to “bing.com”, the mini-browser will come up on the phone and display the following page:

minibrowser

2. Like the Silverlight Button control, HyperlinkButton uses the Content property to set the text for the hyperlink.  Like the Silverlight Button control, anything can be set to the Content.  This means we can use a trick familiar from web development to make an hyperlink look like something else – for instance, an image.

You can create a hyperlink like this:

hyperlink

simply by stacking some controls inside the content of your HyperlinkButton like so:

<HyperlinkButton Name="hyperlinkButton1"  
                    NavigateUri="/MyView.xaml" >
    <Border BorderBrush="White"
            BorderThickness="5"
            Padding="10">
    <StackPanel Orientation="Horizontal">
    <Image Width="60" 
            Source="/phoneapp1;component/Images/appbar.next.rest.png" />
        <TextBlock VerticalAlignment="Center" 
        Text="Go to View.xaml"></TextBlock>
    </StackPanel>
    </Border>
</HyperlinkButton>

3. You can also programmatically navigate between pages.  If your navigation is in the code-behind for a PhoneApplicationPage, you can take advantage of the NavigationService property of your page – which happens to return a System.Windows.Navigation.NavigationService instance.  This service will not only navigate to a page you specify, but will also maintain a history of pages visited in case the end-user decides to use the Windows Phone back button.

 

    this.NavigationService.Navigate(
        new System.Uri(
            "/MyView.xaml"
            ,System.UriKind.RelativeOrAbsolute)
            );

4.  If your navigation code needs to be placed somewhere other than in the code-behind for a PhoneApplicationPage – for instance in a UserControl – things become slightly more complicated.  In this case, the navigation service can be accessed through the PhoneApplicationFrame, which is the root visual for Windows Phone 7 applications.  The Frame has a Navigate method that calls the same NavigationService object we grabbed previously through the page.  The following example accesses the Frame’s navigation method from a Command on a ViewModel.

private void GoToMyView()
{
    var root = App.Current.RootVisual
        as PhoneApplicationFrame;
    root.Navigate(
        new System.Uri("/MyView.xaml"
        ,System.UriKind.RelativeOrAbsolute)
        );
}
private ICommand _navigationCommand;
public ICommand NavigationCommand{
    get
    {
        if (null == _navigationCommand)
        {
            _navigationCommand = new RelayCommand(GoToMyView);
        }
        return _navigationCommand;
    }
}

5. You can finally just change the source property on the PhoneApplicationFrame in order to navigate to a new page.  This is functionally equivalent to calling the Frame.Navigate method – in fact, changing the source property throws an event that ultimately calls the Frame.Navigate method.  The above code can be rewritten to this functionally equivalent code:

var root = App.Current.RootVisual
    as PhoneApplicationFrame;
root.Source =
    new System.Uri("/MyView.xaml"
    ,System.UriKind.RelativeOrAbsolute);