Patterns of Windows Phone Architecture Part II

When the WP7 beta dev tools were released, developers were pleased to find several new events hanging off of Shell.PhoneApplicationService for managing a phone application’s life cycle: Launching, Closing, Activated and Deactivated.  The first two events are obviously thrown when an application is first launched and when it is closed down (either by hitting the back button past the first page in the app or, interestingly, by throwing an unhandled exception).

The Activated and Deactivated events are thrown when the application is interrupted mid-run – typically by launching a Windows Phone task or by hitting the Windows button on the phone.  This is a scenario known as tombstoning.

If you are not yet familiar with the concept of tombstoning or simply need a refresher, please read Yochay Kiriaty’s post on the subject here.

These new events give Silverlight for WP7 developers a way to manage application state outside of the navigation events on each page.  Two design considerations must be taken into account, however, in order to take advantage of this centralized way of persisting state information.  1. All data that needs to be persisted between application runs or during tombstoning must be accessible from the event handlers for the four lifecycle events.  2. If application data persistence is handled outside of each page, another mechanism is required for persisting page state information as well as model data between page instantiations.

2. Anchor ViewModel

The Pledge

An anchored boat is able to stay in one place while currents wash away unmoored items floating on the ocean.  Anything tethered to the boat, or tethered to something tethered to the boat, is likewise stationary.  This is the main concept behind an Anchor ViewModel phone architecture.

While the developer has little control over the lifespan of a PhoneApplicationPage, he can nevertheless control the life of the state of the page if he is using an M-V-VM pattern.  There are several artifacts in the application that ViewModels can be tethered to and which survive the constant newing up and dereferencing of Views in a Silverlight app for the phone.  The Application itself can serve as an anchor.  It has a RootVisual, the PhoneApplicationFrame, which hosts (typically) a MainPage.xaml PhoneApplicationPage that doesn’t go out of scope until the application is terminated.  ViewModels can be tethered to any of these objects in order to give them a lifespan beyond the lifespan of their respective Views.

The Windows Phone Databound Application Template that is provided with Visual Studio for Windows Phone demonstrates this anchoring technique.  In this sample template, the MainViewModel object hangs off of the App class.  When the MainPage view is instantiated, the App’s MainViewModel instance is assigned to the MainPage view’s DataContext. At this point, the lifecycle of MainViewModel is tethered to the lifecycle of App rather than to the lifecycle of MainPage.

The DetailsPage view, in turn, retrieves its DataContext from a ViewModel hanging off of MainViewModel which hangs off of App.  The lifecycle of the ItemViewModel is tethered to the lifecycle of MainViewModel which in turn is anchored to the App class.

The Turn

This is more evident if we change the default application based on the Windows Phone Databound Application Template a little.  First, MainViewModel can be modified to include a SelectedItem property:

private ItemViewModel _selectedItem;
public ItemViewModel SelectedItem 
{
    get { return _selectedItem; }
    set 
    { 
        _selectedItem = value;
        NotifyPropertyChanged("SelectedItem");
    }
}

Then the ListBox in MainPage.xaml should have it’s SelectedItem attribute bound to this property:

<ListBox x:Name="MainListBox" 
            SelectedItem="{Binding SelectedItem, Mode=TwoWay}" 
            ItemsSource="{Binding Items}"

We simplify the MainListBox’s SelectionChanged event handler like so:

// Handle selection changed on ListBox
private void MainListBox_SelectionChanged(object sender
    , SelectionChangedEventArgs e)
{
    // If selected index is -1 (no selection) do nothing
    if (MainListBox.SelectedIndex == -1)
        return;

    // Navigate to the new page
    NavigationService.Navigate(new Uri("/DetailsPage.xaml"
        , UriKind.Relative));
}

Finally, in our details page, we would set the DataContext in the constructor rather than in the OnNavigatedTo method:

public DetailsPage()
{
    InitializeComponent();
    if (DataContext == null)
        DataContext = App.ViewModel.SelectedItem;
}

The point to remember here is that when the DetailsPage view goes out of scope through a back page navigation, the VM for DetailsPage continues to exist in memory and remains accessible because it is tethered to MainViewModel. 

More importantly, if we change a property on the ItemViewModel we are using for the DataContext of DetailsPage, these changes would be persisted back to MainViewModel after we navigate away from DetailsPage, and would remain persisted for as long as the current App is held in memory.

The Prestige

The payoff to this pattern is that we can now handle tombstoning by persisting all of our VMs centrally in a few lines of code:

string _appToken = "all_vms";

private void Application_Activated(object sender
    , ActivatedEventArgs e)
{
    var store = PhoneApplicationService.Current.State;
    if (store.ContainsKey(_appToken))
        viewModel = store[_appToken] as MainViewModel;
}

private void Application_Deactivated(object sender
    , DeactivatedEventArgs e)
{
    var store = PhoneApplicationService.Current.State;
    if (store.ContainsKey(_appToken))
        store[_appToken] = viewModel;
    else
        store.Add(_appToken, viewModel);
}

Because all view models are anchored to MainViewModel, saving our top level view model will also automatically serialize and later deserialize all the of VMs hanging off of MainViewModel as well as the state of their properties.

We have effectively made the entire default Databound Phone Application sample “tombworthy”.   If you now tombstone the application while navigated to the DetailsPage (for instance by pressing the Windows button at bottom center), it will be restored when you return to the application.

In an application with 5, 10 or more VMs, this will be very handy.

The next post in this series will cover the Satellite ViewModels pattern, which uses many of the same principles but allows greater control over how and what state gets persisted.

 

 

WP7 Tip: don’t use the unlocked ROM for development

One of the frustrations of developing for Windows Phone 7 is that, without a device in hand, it is hard to understand what the phone actually looks like.  It is useful to be able to see how Microsoft implements the built in applications in order to borrow ideas for hubs, transitions, and general look-and-feel.

Enterprising developers quickly built an “unlocked” version of the July emulator image that allows developers to see more of the features and design of the phone in their emulator software.

You should not use the unlocked ROM image for development, however.  One problem that has come up concerns making https service calls from an application running in the unlocked image.

If you try to call an https service from the unlocked ROM, you are likely to receive a variation on the Page Not Found error.  To verify that this is a problem with the ROM image and not with your code, open up Internet Explorer and try to navigate to a site such as https://careers.microsoft.com/ .  If you receive an error, then the issues are likely not with your code but with the emulator image you are using.  Switch back to using the official developer image that is installed with the Windows Phone developer tools beta and your web service issues should go away.

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.

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);

Free Windows Phone 7 Devices

startscreen_print

According to the twitter rumor mill, certificates for free Windows Phone 7 devices are being handed out to select attendees at this year’s Tech-Ed North America in New Orleans (to be accurate 50 of them, according to Brandon Watson).

Looking past some of the grumbling from a few MIX10 attendees who feel they should have gotten a shot at the phones (we all got free Azure t-shirts left in our hotel rooms, didn’t we?), this is very exciting news.  It suggests that a large number of Windows Phone devices are ready and will soon become available to WP7 developers.

<hypothetical>WP7 DEVICES for Phone application developers will soon be generally – more or less — AVAILABLE!  Woohoo!</hypothetical>

For the past month or so I’ve been peering at these devices over the shoulders of Microsoft evangelists.  At MIX I surreptitiously saw one hanging out of the pocket of a project manager on the Phone team.  I don’t think I even saw one at the MVP Summit in February.

So how does one get one’s hands on the upcoming series of phones for developers?  I have no hard information, but a good bet is to sign up for the Windows Phone Marketplace.

It’s $99 for a year – a very good price if you plan to develop Windows Phone applications in time for the Holiday launch later this year.  And if, by chance, that registration puts you on a list to potentially get a WP7 device – well that’s just gravy, isn’t it?

The big message I’m hearing, though, is that you should really come up with a great idea for a phone app before asking for a phone.  Microsoft isn’t looking to hand out phones so you can, only at that point, start thinking about what you might want to build.  That would be putting the cart before the handheld device.