Getting the current theme in WP7 for Silverlight

Customizing App.xaml.cs

Windows Phone devices allow users two theme options, either dark or light.

In the WP7 beta dev tools, however, there no straight-forward way for Windows Phone Silverlight developers to find out what the current theme is, though there is a hack.  The developer must interrogate the app resources to find the color of the PhoneBackGroundColor.  Under the dark theme it is black, while under the light theme it is white.

The following code can be thrown into App.xaml.cs to add a little elegance to this hack. 

First, a brief enum is needed.  It can be added in App.xaml.cs above the App class, or simply placed in its own cs file in the project:

public enum Theme{Light,Dark}

A CurrentTheme property is added to the App class:

private static Theme _currentTheme;

public static Theme CurrentTheme
{
    get { return _currentTheme; }
    private set { _currentTheme = value; }
}

And then we assign a value to CurrentTheme in the App class constructor by interrogating Resources:

public App()
{
    var bgc = Resources["PhoneBackgroundColor"].ToString();
    if (bgc == "#FF000000")
        CurrentTheme = Theme.Dark;
    else
        CurrentTheme = Theme.Light;

    //etc.

The CurrentTheme is now retrievable from anywhere in the application like so:

    switch(App.CurrentTheme)
    {
        case Theme.Dark:
            MessageBox.Show("Dark");
            break;
        case Theme.Light:
            MessageBox.Show("Light");
            break;
    }

Moreover, if a user presses the Windows button at lower center on a device and resets the theme, the new theme will be assigned to CurrentTheme when the application returns from tombstoning.

There is a rumor that in the RTM of the WP7 dev tools, two new properties will be available for picking up the current theme: DarkThemeVisibility and LightThemeVisibility.

For ease of migration to the RTM, you can add the following two properties to App.xaml.cs for now as placeholders – you should be able to simply switch them out later should the new methods become available:

public static bool DarkThemeVisibility
{
    get { return CurrentTheme == Theme.Dark; }
}

public static bool LightThemeVisibility
{
    get { return CurrentTheme == Theme.Light; }
}

How to Quit a WP7 Silverlight Application

Customizing App.xaml.cs

In the current Beta dev tools for Windows Phone 7, there is no way to exit a Silverlight application (though there is a method to do this for XNA apps).

Currently the best way – and I use the term “best” loosely – to do this is to throw an exception.  An unhandled exception always manages to kill your application.

If we must use a hack, however, we might as well  do it with a bit of finesse.  Below is a simple implementation that can be placed in the App class of a WP7 Silverlight project that clarifies the behavior of the app when we intentionally throw an exception in order to exit rather than simply throwing an exception exceptionally.

This code can be called from anywhere in your app in order to Exit predictably.

Here is the call:
App.Quit();
And here is the implementation in App.xaml.cs:
private class QuitException : Exception { }

public static void Quit()
{
    throw new QuitException();
}

private void Application_UnhandledException(object sender, 
    ApplicationUnhandledExceptionEventArgs e)
{
    if (e.ExceptionObject is QuitException)
        return;

    if (System.Diagnostics.Debugger.IsAttached)
    {
        System.Diagnostics.Debugger.Break();
    }

    //etc.
}
Windows Phone 8 Update

If you are doing Windows Phone 8 development, things get easier.  After having so many apps going through the store using the above method to exit out, the WP Dev\Design team decided to just implement their own escape method.  Sometimes the doctor is right and sometimes the patient just has a better understanding of what the pain feels like.  To exit out of a Windows Phone 8 app, call Application.Terminate .

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.

 

 

Patterns of Windows Phone Architecture Part 1

The Windows Phone platform introduces several problems for the software architect which, if not completely absent in standard Silverlight applications, are nevertheless more acute. The most important of these revolve around state: the state of data during the running of an application and the state of the data between runs.

Because Windows Phone design is structured around the phone navigation frame, a Silverlight out-of-browser application on the phone behaves more like a web application than a stateful application.  The lifespan of a typical PhoneApplicationPage is uncertain. 

While the first page in a Phone application’s backstack (usually MainPage.xaml) is tied to the lifespan of the application itself, all other pages are only accessible while currently displayed or existing in the backstack.  By existing on the backstack, I here mean accessible 1. by pressing the back button and 2. by calling NavigationService.GoBack() .

Once a page is no longer visible because a user has navigated back, it is no longer accessible whether it has been garbage collected or not.  In this sense, typical concepts of garbage collection are not really relevant. 

Once you have navigated backwards, the same instance of the page cannot be retrieved.  For instance, in the scenario where a user begins at MainPage.xaml and then navigates forward to DetailsPage.xaml, then navigates back to MainPage again, an additional navigation forward to DetailsPage.xaml will create a new instance of Details.  The original instance is lost and is no longer accessible.

To make matters more difficult, if the the application launches a task based on user input, the Details page is once again lost.  When the user clicks back to return to the application from a launcher or completes a chooser task, a new instance of DetailsPage will be created.  When the user clicks back from DetailsPage, a new instance of MainPage will be instantiated.  This termination of the current application in order to run task is known as “tombstoning”.

A final problem regarding state occurs if the phone application makes calls to web services.  Because web services are much more expensive and time sensitive than on typical web applications, it is highly desirable to cache data that has been retrieved from a service.

We’ll categorize these problems as problems of 1. page data state, 2. application data state and 3. model data state, respectively.

In this post I will outline three architectural patterns for solving these three problems of state in a Windows Phone application.  The patterns are View-ViewModel Pairing, Satellite ViewModels and Anchor ViewModels.

In the following posts, I will go in depth into the implementation each approach as well as provide helper classes and recommended coding patterns.  Finally, I will show how they can be incorporated into existing frameworks and techniques such as MVVM Light, Caliburn Micro and IOC.

I. View-ViewModel Pairing (Buddy System)

The View-ViewModel Pairing pattern is based on a persistence pattern recommended during the CTP stage of the Phone Development Tools.  In this pattern, each page or view (MainPage, DetailsPage, etc.) is responsible for the persistence of its data each time the page is added to or leaves the backstack. 

In the CTP, this was often illustrated by saving the data for a particular control on the view (current.State is used here, but isolated storage would work just as well):

string token = "myToken";

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    var store = PhoneApplicationService.Current.State;
    if (store.ContainsKey(token))
    {
        string txt = store[token] as string;
        if (txt != null)
            this.textBox1.Text = txt;
    }
}

protected override void OnNavigatedFrom(NavigationEventArgs e)
{
    var store = PhoneApplicationService.Current.State;
    if (store.ContainsKey(token))
        store[token] = textBox1.Text;
    else
        store.Add(token, textBox1.Text);
}

This becomes cumbersome, however, if more than a few properties require persistence.  A better approach is possible if the phone application uses M-V-VM in its design (or really any UI Design Pattern that takes advantage of the DataContext property).  In this case, we can simply persist the entire VM rather than iterate through each control.  The above code can be simplified like this:

public Page1()
{
    InitializeComponent();
    this.Loaded += new RoutedEventHandler(Page1_Loaded);
}

void Page1_Loaded(object sender, RoutedEventArgs e)
{
    if (this.DataContext == null)
        this.DataContext = new Page1ViewModel();
}

string token = "myToken";
protected override void OnNavigatedTo(NavigationEventArgs e)
{
    var store = PhoneApplicationService.Current.State;
    if (store.ContainsKey(token))
        this.DataContext = store[token] as string;
}

protected override void OnNavigatedFrom(NavigationEventArgs e)
{
    var store = PhoneApplicationService.Current.State;
    if (store.ContainsKey(token))
        store[token] = this.DataContext;
    else
        store.Add(token, this.DataContext);
}

This pattern collapses the problems of page data persistence and application data persistence by saving both off at the same time.

On the first navigation to this page, the Loaded event handler news up the datacontext.  On subsequent visits to the page, the DataContext is set in the OnNavigatedTo event handler.  Because Loaded fires after OnNavigatedTo, the DataContext is not set there.  Each visit to this page will always retrieve the same ViewModel data from state, whether the View is itself new or not.

This solution also works in cases where the application has been tombstoned.

If IsolatedStorage is used instead of PhoneApplicationService.Current.State, the ViewModel will even survive between runs of the application.

Finally, because any data retrieved from a web service is typically fed into an ObservableCollection on the ViewModel, the serialization/deserialization process will also typically take care of caching relevant model data.

There is one significant shortcomings to using the Buddy System.  Because there is no way (at least in the beta) to find out in the OnNavigatedTo event handler if we are returning from a tombstoned state or simply returning from a subsequent page through the back button, we may be re-hydrating the ViewModel unnecessarily.

(To be continued …)

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 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.

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