Category Archives: WP7

Windows Phone Toolkit - September 2012 Release

A few astute people (@Patric68@scottisafool) have noticed that we pushed out the September 2012 release of the Windows Phone Toolkit.  This was a soft launch, quietly pushed out because we’ve been going like crazy with bug fixes, prepping for Build and doing a whole host of things and I really wanted to get a build out that had the latest fixes and improvements without blocking on all the paperwork. That’s agile baby!

What’s New

Branding

It’s now just the “Windows Phone Toolkit”.  Honestly “Silverlight for Windows Phone Toolkit” was too much of a mouthful and new developers targeting Windows Phone often don’t know of the Silverlight underpinnings.  We’re slowly transitioning all branding in the source to the shorter version.

CustomMessageBox

Sample CustomMessageBox Image

CustomMessageBox is a new control that makes it easy to create, well, custom message boxes that look and feel just like the default ones on the phone.  I did a little write-up of it last week in my blog post, “Welcome CustomMessageBox to the Windows Phone Toolkit”.

Rating

Sample Rating Control Image

Rating is another new control that does exactly what it says, provides a rating control that matches the Windows Phone UI.  Expect a blog post on using it soon but it as always you can see it in action by downloading the sample application from CodePlex.

Transition Effects

There are new transition effects that make it even easier to match the Windows Phone UX.

  • SlideInEffect – Ever notice when you’re in a Pivot or Panorama on the phone in one of the native experiences , say the People Hub, how the items in a list slide in on a separate animation as you swipe back and forth?  It’s subtle but adds a nice level of polish to the whole experience and now it’s super easy to add to your application as well.  There is a new attached property, toolkit:SlideInEffect that you set on each item in your DataTemplate that controls the order in which elements slide in:
    <DataTemplate>
        <StackPanel Margin="0,0,0,17" Width="432">
            <TextBlock Text="{Binding LineOne}" 
                       TextWrapping="Wrap" 
                       Style="{StaticResource PhoneTextExtraLargeStyle}"/>
            <TextBlock Text="{Binding LineTwo}" 
                       TextWrapping="Wrap" 
                       Margin="12,-6,12,0" 
                       Style="{StaticResource PhoneTextAccentStyle}"
                       toolkit:SlideInEffect.LineIndex="1"/>
            <TextBlock Text="{Binding LineTwo}" 
                       TextWrapping="Wrap" 
                       Margin="12,-6,12,0" 
                       Style="{StaticResource PhoneTextSubtleStyle}"
                       toolkit:SlideInEffect.LineIndex="2"/>
        </StackPanel>
    </DataTemplate>
  • FeatherTransition – Another common effect seen on Windows Phone is a “feathering” in of the controls on a page such as when you launch the mail app.  Notice how the items on the page feather in from top to bottom.
    <!--TitlePanel-->
    <StackPanel Grid.Row="0" Margin="12,17,0,28">
        <TextBlock Text="{StaticResource ApplicationTitle}" 
                    Style="{StaticResource PhoneTextNormalStyle}"
                    toolkit:TurnstileFeatherEffect.FeatheringIndex="0"/>
        <TextBlock Text="turnstilefeathereffect" 
                    Margin="9,-7,0,0" 
                    Style="{StaticResource PhoneTextTitle1Style}"
                    toolkit:TurnstileFeatherEffect.FeatheringIndex="1"/>
    </StackPanel>

Distribution / Installation

We’ve taken a new approach to distribution this time and gone “all-in” on NuGet as the official way to install the toolkit.  We’ll no longer be supporting an MSI-based installer as it’s not very maintainable or discoverable.  NuGet is built into Visual Studio 2012 and is fast becoming the de-facto standard for installing packages and if you haven’t already installed the plug-in for Visual Studio 2010 I highly recommend it.

As always you can still either download the source as a zip or from the source control on CodePlex and compiling the assembly yourself.

Bug Fixes

No release is complete without bug fixes and we have roughly 25 of the top user voted bugs fixed in this release.

Feedback

As always we love feedback, bug reports, creative uses and ideas.  We have more plans for the toolkit in the near future as well so stay tuned!

Welcome CustomMessageBox to the Windows Phone Toolkit

A big welcome to CustomMessageBox, a new control to the toolkit which is exactly what it sounds like, a customizable, Windows Phone-UI compliant, easy to use message box offering the following features:

  • Native look & feel including font sizes, layout, alignment and animations
  • Ability to display full screen or to only consume as much space as needed
  • Very simple “basic” mode with ability to easily extend it to complex scenarios
  • Customizable buttons without needing to re-template

Here is what it looks like, from the basic (a message and some buttons) to the complex (a full screen message box with an embedded Pivot):

imageimage

Getting Started

As of today (9/30/2012) you’ll need to download the latest source from CodePlex and recompile the toolkit assembly to use it but we’ll soon have an updated NuGet package for your convenience. As usual add a reference to the Microsoft.Phone.Controls.Toolkit.dll to your project and add the toolkit XML namespace to the top of your XAML:

xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

Basic Usage

The basic usage is very similar to the default MessageBox and how you’re probably used to using dialogs in other UI platforms; set some properties, call Show(), handle the event that is raised when the user returns from the dialog.

Possible values to customize are:

  • Caption – sets the title caption of the message box
  • Message – the actual message to display to the user
  • LeftButtonContent, RightButtonContent – the buttons that appear on the bottom of the dialog, if you omit the text then the button won’t be shown.

To handle the user’s selection hook up the Dismissed() event and look at the e.Result value which is of type CustomMessageBoxResult indicating which, if any, button was tapped. If the user presses the back button vs. making a selection the result will be None.

Finally to kick-off the whole process call Show(). Show() is non-blocking so be aware that any code you put after the Show() call will run before the user has made a selection.

By default the the message box only takes up as much space as required but you can force it to full-screen by setting the property IsFullScreen to true.

Simple Example

To recreate the first message box in the screen shot do the following in code-behind:

CustomMessageBox messageBox = new CustomMessageBox()
{
    Caption = "Do you like this sample?",
    Message = "There are tons of things you can do using custom message boxes. To learn more, be sure to check out the source code at CodePlex.",
    LeftButtonContent = "yes",
    RightButtonContent = "no"
};
messageBox.Dismissed += (s1, e1) =>
    {
        switch (e1.Result)
        {
            case CustomMessageBoxResult.LeftButton:
                // Do something.
                break;
            case CustomMessageBoxResult.RightButton:
                // Do something.
                break;
            case CustomMessageBoxResult.None:
                // Do something.
                break;
            default:
                break;
        }
    };
messageBox.Show();

The title caption, message and buttons are configured, the Dismissed() event is assigned a handler and finally the Show() method is called to kick off the party.

Taking It Up A Notch

That’s all well and good but where is the real “custom” part of the CustomMessageBox? That comes in with the Content property where you insert your own content into the overall layout. You can define your extra content in either code-behind or as a XAML resource and then set it to the Content of the CustomMessageBox.

The content area exists below where the Message is displayed yet right above the buttons.

Let’s say we want to recreate this dialog:

image

Via Code-Behind

One way to go about it would be to create all the custom content inline at the time of invocation:

HyperlinkButton hyperlinkButton = new HyperlinkButton()
{
    Content = "Privacy Statement",
    Margin = new Thickness(0, 28, 0, 8),
    HorizontalAlignment = HorizontalAlignment.Left,
    NavigateUri = new Uri("http://silverlight.codeplex.com/", UriKind.Absolute)
};
TiltEffect.SetIsTiltEnabled(hyperlinkButton, true);
CustomMessageBox messageBox = new CustomMessageBox()
{
    Caption = "Allow this application to access and use your location?",
    Message = "Sharing this information helps us provide and improve the location-based services offered for this phone. We won't use the information to identify or contact you.",
    Content = hyperlinkButton,
    LeftButtonContent = "allow",
    RightButtonContent = "cancel"
};

The HyperlinkButton is created in code, tilt effect is set on the HyperlinkButton and to hook it together the HyperlinkButton is assigned to the Content property.

Via XAML

Another approach is to create it as a DataTemplate in either the page or application resources and when you configure the dialog set the ContentTemplate property which may prove easier for more complicated templates.

<DataTemplate x:Key="HyperlinkContentTemplate">
    <HyperlinkButton Content="Privacy Statement"
                        Margin="0,28,0,8"
                        HorizontalAlignment="Left"
                        NavigateUri="http://silverlight.codeplex.com/"
                        TargetName="_blank" />
</DataTemplate>

Now the code-behind looks like this:

CustomMessageBox messageBox = new CustomMessageBox()
{
    Caption = "Allow this application to access and use your location?",
    Message = "Sharing this information helps us provide and improve the location-based services offered for this phone. We won't use the information to identify or contact you.",
    ContentTemplate = (DataTemplate)this.Resources["HyperlinkContentTemplate"],
    LeftButtonContent = "allow",
    RightButtonContent = "cancel"
};

More Samples

You can find more examples, including the source to the “What Can I Say?” screenshot I showed above, in the Toolkit Samples project which you can either get via downloading the latest source or looking at it directly on CodePlex.

As always feedback is appreciated via either comments here or on CodePlex. We review each piece of feedback and we do get to them, if sometimes a little later than we’d like. Our goal is to make it so you can focus on writing your application vs. having to recreate the UI you see on the phone.

How to make the Windows Phone Toolkit ToggleSwitch Header wrap

I’m going through the Windows Phone Toolkit bugs fixing some of the low hanging fruit and came across this bug where a ToggleSwitch with a long header is clipped.  The proper Metro behavior is that it should wrap which is easy enough to do on a TextBlock.  The rub though is that the Header is represented by a ContentControl, not a TextBlock.

ContentControl makes it easy to put whatever you’d like into the Header; images, other controls, buttons, etc. and is the standard Silverlight way of representing content.  This is great for an open-ended environment like the Silverlight plug-in where each app has it’s own UI but on the phone you want as close to the Metro UI as you can get.  In a perfect world (or just one with a time machine) we would have made Header a TextBlock with wrapping turned on but, well, we didn’t.  We’re still debating if we should just make the switch and deal with the fall out but until then here is a super simple way to ensure your Header text wraps when it needs to:

<toolkit:ToggleSwitch Header="This is an example of a really long description label for localization">
    <toolkit:ToggleSwitch.HeaderTemplate>
        <DataTemplate>
            <TextBlock FontFamily="{StaticResource PhoneFontFamilyNormal}"
                        FontSize="{StaticResource PhoneFontSizeNormal}"
                        Foreground="{StaticResource PhoneSubtleBrush}"
                        TextWrapping="Wrap"
                        Text="{Binding}" />
        </DataTemplate>
    </toolkit:ToggleSwitch.HeaderTemplate>
</toolkit:ToggleSwitch>

Which gets you:

image

If you’re going to do any type of localization I recommend you make this change to all your ToggleSwitch controls.

Unable to Clear East Asian Text from a TextBox in Windows Phone (or always clear your TextBox focus)

We’ve received several reports of apps that don’t clear out their text even though the app author is setting the Text property to an empty string.  I did a little poking and it’s due to a combination of the application bar and IME.  The onscreen keyboard (SIP) enters a composition mode when working with East Asian languages that allows for quickly entering complex words and phrases and it ends once the SIP is dismissed.  If the text is modified programmatically while it’s in this mode it’ll behave unpredictably, the most obvious issue being that it doesn’t update to reflect the text you’ve set in your code behind.

You can tell if a TextBox is in this mode by the underline underneath the current character you’re editing:

image

Because the ApplicationBar isn’t drawn or managed by Silverlight focus won’t properly be taken away from the currently active control (the TextBox) and any attempt to change the text via the Text property will put the TextBox into the state I mentioned above.  The most common way this happens is performing some action on the text such as sending a message and then attempting to clear it out.

private void ApplicationBarIconButton_Click(object sender, EventArgs e)
{
    ChatUpFriend(MessageTextBox.Text);
    MessageTextBox.Text = "";
}

Luckily the work around is easy, force the SIP to be dismissed before clearing the Text property and everything will work as expected.  The most common/easiest way is to set focus to the page itself:

private void ApplicationBarIconButton_Click(object sender, EventArgs e)
{
    // Set focus to the page ensuring all TextBox controls are properly commited
    // and that the IME session has been correctly closed.
    this.Focus();
    ChatUpFriend(MessageTextBox.Text);
    MessageTextBox.Text = "";
}

I recommend putting this code anywhere you’re clearing out a TextBox as you never know what language your users will be typing in.

Using RestSharp with AgFx in your Windows Phone app

I’m using the excellent REST library RestSharp for all my REST and OAuth calls.  I’m also using the amazing data caching framework AgFx written by Shawn Burke which handles caching your web requests, something that goes from a nice to have to critical when writing high performance Windows Phone apps.

Out of the box AgFx handles all your requests so it can do it’s caching thing, getting in the front of each request to determine if it should give you a cached version instead of hitting the web, if it should invalidate the cache, if it should give you a cached version and then make a live request, etc.  This is how you want it but sometimes you want more control over how those live requests are made.  In my case I’m using OAuth and requesting protected resources that require OAuth access tokens and RestSharp has some very nice methods for both authenticating and making those pesky protected calls.  The question is how to slip RestSharp into the middle of the AgFx mechanism?

AgFx Out of the Box

Your basic AgFx call looks like this:

ZipCodeVm viewModel = DataManager.Current.Load<ZipCodeVm>(txtZipCode.Text);

Which eventually executes code like this (which you the developer has written):

public LoadRequest GetLoadRequest(ZipCodeLoadContext loadContext, Type objectType)
{
    // build the URI, return a WebLoadRequest.
    string uri = String.Format(ZipCodeUriFormat, loadContext.ZipCode);
    return new WebLoadRequest(loadContext, new Uri(uri));
}

AgFx will call GetLoadRequest() to get a LoadRequest which it’ll use when it needs to fetch live data.  This example is using the default WebLoadRequest which uses HttpWebRequest under the covers to fetch the data but as long as you return an object that descends from LoadRequest you can use whatever requesting mechanism you like.

RestSharpLoadRequest

That’s where RestSharp comes in.  Instead of hand-crafting HTTP requests including hand-crafting headers and building POST payloads I’m going to let RestSharp do the heavy lifting by creating a custom RestSharpLoadRequest.  It’s based heavily on the WebLoadRequest in AgFX, right down to the comments and took all of 15 minutes to code up.  It’s not that exciting of a class but you can download it and view it on github as a gist:

An AgFx LoadRequest that uses RestSharp to make the actual request, supports passing in OAuth tokens

Download it and drop it into your application as is (well, I’d probably change the namespace to something more appropriate).  Sorry about it being a tar.gz file, maybe I’ll ping Phil Haack now that he works there to offer up .zips for gists as well.

WOW, sorry folks, I didn’t realize I’d created the Gist as private, if you tried to view it before you should have better luck now.

RestSharpLoadRequest in Action

I’m going straight to a meaty example where I create a few parameters to throw on the URL and pass in all my OAuth token goodness:

public LoadRequest GetLoadRequest(ShelfLoadContext loadContext, Type objectType)
{
    var resource = BuildResource(
        "review/list.xml",
        new Dictionary()
        {
            {"v", "2"},
            {"id", loadContext.UserId},
            {"page", loadContext.Page.ToString()},
            {"shelf", loadContext.Shelf}
        });
    return new RestSharpLoadRequest(
        loadContext,
        resource,
        Client.Current.ConsumerKey,
        Client.Current.ConsumerSecret,
        Client.Current.AccessToken,
        Client.Current.AccessTokenSecret);
}

Don’t worry about the BuildResource call, that’s simply building up your REST API end-point (aka “resource”).  The only difference from the standard usage of AgFx is instead of a WebLoadRequest I’m using RestSharpLoadRequest.

And there you have it, now you can lean on RestSharp inside of the AgFx framework.  Also If you’re using Hammock as your REST library as choice it should take all of 15 minutes to whip up a HammockLoadRequest following the same basic principles.

UPDATE (02.14.2010): The way I was handing parameters above was just plain weird, the RestRequest object that I’m using inside of RestSharpLoadRequest already has robust AddParameter() logic so I exposed it.  The above code now looks like this:

public override LoadRequest GetLoadRequest(ShelfLoadContext loadContext, Type objectType)
{
    var request = new RestSharpLoadRequest(
        loadContext,
        GoodReadsClient.Current.BuildResource("review/list.xml"),
        GoodReadsClient.Current.ConsumerKey,
        GoodReadsClient.Current.ConsumerSecret,
        GoodReadsClient.Current.AccessToken,
        GoodReadsClient.Current.AccessTokenSecret);
    request.AddParameter("key", GoodReadsClient.Current.ConsumerKey);
    request.AddParameter("shelf", loadContext.Shelf);
    request.AddParameter("v", "2");
    request.AddParameter("id", loadContext.UserId);
    request.AddParameter("page", loadContext.Page.ToString());
    return request;
}

Not only does it leverage existing code it follows the pattern most RestSharp/Hammock users are used to, namely you create the request and then you add on parameters.

Recreating the Windows Phone 7 message “bubble” style in Silverlight

In a little app I’m working on to exercise some new Mango features I needed to create the message “bubble” and oddly enough didn’t stumble across any samples I could easily use even though a large number of apps have recreated this style, most likely because it’s so easy to do.

image

Here was my first take and it’s very hard-coded to the above look but it should be trivial to change it around.  Also there are dozen ways you could make this more reusable, either as a template for a ContentControl or as a new control.  If anyone has any suggestions for improvements or a better resource I’d love to see it!

XAML

<!-- bubble -->
<Grid Grid.Column="1"
		Margin="12,6,12,0">
	<Grid.RowDefinitions>
		<RowDefinition Height="Auto" />
		<RowDefinition Height="Auto" />
	</Grid.RowDefinitions>
	<Path Data="M 16,12 16,0 0,12"
			Fill="{StaticResource PhoneAccentBrush}"
			HorizontalAlignment="Right"
			Margin="0,0,12,0"
			UseLayoutRounding="False"
			VerticalAlignment="Top" />
	<!-- Your actual content here -->
	<StackPanel Grid.Row="1"
				Background="{StaticResource PhoneAccentBrush}">
		<TextBlock Text="{Binding Mood}"
					Style="{StaticResource PhoneTextNormalStyle}"
					FontWeight="Bold"
					TextWrapping="Wrap"
					Margin="6,12,6,6"
					HorizontalAlignment="Left"
					VerticalAlignment="Top" />
		<TextBlock Text="{Binding LastUpdated, StringFormat='g'}"
					HorizontalAlignment="Right"
					VerticalAlignment="Top"
					Margin="6,0,6,6"
					Style="{StaticResource PhoneTextSubtleStyle}"
					FontFamily="Segoe WP SemiLight" />
	</StackPanel>
</Grid>

Note for the sharp-eyed I’m using a feature that is new for Mango that exists in Silverlight 4 which is default string formatting in bindings.

Extension method to get a page’s ProgressIndicator

In Mango we added the ability to interact with the shell’s native progress indicator along the top of the page.  This is a great way to maintain UI consistency with the phone as well as get a smooth progress animation because the system is handling the animation vs. the Silverlight runtime.  Here I’m recreating the ‘save to phone’ menu item you can see in the pictures hub by adding a “Saving picture…” progress indicator:

image

There are some great articles on using the new ProgressIndicator out there and I won’t do yet another intro blog post but I did want to share a little extension method I wrote to grab it from the page and avoid some of the annoying initialization code that you end up writing over and over again.

Some of my favorite ProgressIndicator articles so far for those looking to explore this in more depth are:

And here is my little extension method I’ve found useful on a few pages:

public static class Extensions
{
    public static ProgressIndicator GetProgressIndicator(this PhoneApplicationPage page)
    {
        var progressIndicator = SystemTray.ProgressIndicator;
        if (progressIndicator == null)
        {
            progressIndicator = new ProgressIndicator();
            SystemTray.SetProgressIndicator(page, progressIndicator);
        }
        return progressIndicator;
    }
}

I’m playing with using some of the various code snippet websites out there and this is embedded from Smipple. I’d love to see more Windows Phone snippets pop up on these sites.

UPDATE: Scratch the idea of embedding Smipple snippets via embed code, it looks awesome but seems to tweak my formatting, going back to good old syntax highlighted.

What’s New for Windows Phone Development with Silverlight (in Mango) - MIX11 Session Online

My talk from MIX11 has made its way online and for those that couldn’t attend (or those that were still recovering from the great attendee party and discovered that 9am is way too early to attempt to move) a video of my session is online over only channel9 available for streaming or downloading.

Channel9: What’s New for Windows Phone Development with Silverlight?

Also for your direct viewing pleasure here it is embedded.

For anyone that watches it and has questions, or people in the audience that didn’t get a chance to ask one feel free to drop me a line in the comments and I’ll do the best I can to find you the answers.

Also because not everyone had time to fill out their speaker evals if there is a type of content or way you’d like to see this content delivered in the future I’d love to hear your feedback in general.  More or less code? More technical details, would you prefer to see flashy demos that rock but require a lot of code or more simple demos that clearly show the feature?

MIX is for you so anything we can do to help improve content is greatly appreciated.