Posts Tagged ‘Silverlight’
January 25th, 2012
So, you want to use Facebook to sign into something or in some way integrate Facebook with your Windows Phone 7 app. You are in luck because it is almost hilariously easy.
I’ve uploaded this tutorial as a zip file. I tried to github it, but I’m inching up on 1 hour of trying to figure out what the hell I’m doing wrong.
Download this Tutorial Project
I’ve tried to make this a full featured tutorial, so if you just want to get to the code, head down to the “Let the User Login To Facebook” section.
Get Your Facebook Key
Go to http://developers.facebook.com and log in with your Facebook account. Give them the permissions they need and go to the “Apps” tab. Click on “Create new App”
Fill in the App Display Name and the App Namespace and do the verification. Then you’ll get to a page that gives you your App ID and App Secret.

Don’t worry about anything else here… you don’t need to select anything in the “how your app integrates with Facebook” section to do this tutorial. If you’re using Facebook integration to do some basic login and simple posting, you could probably just use the Website option.
Also, click the “Graph API Explorer” on the left and keep that open. We’ll come back to that in a moment.
Add Facebook C# SDK
Download the Facebook C# SDK and extract it. Go to the “sl3-wp” folder and unblock the Facebook.dll file (right-click => Properties=>click “Unblock”)
Open up your project (for the example, I used the Visual Studio 10 “Windows Phone Databound Application” template) and right-click on “References => Add References…”. Click “Browse” and navigate to the Facebook.dll and add it to your project.
Build Facebook Login UI
We’ll do this quick here (no MVVM, no bindings) but in later versions I’ll integrate this into a more formal project.
Open your project in Blend. For this quick-and-dirty tutorial, we’ll just add another page title and another panel for the UI we want to show when the user is logged in and set the Visibility to Collapsed on those. Our visual tree should look like this.

In our loginPanel, we’re going to add a button and a WebBrowser to our panel. Set the button (containing “sign in using facebook” in the content) to the top and the WebBrowser to fill the panel. For a little flare, I’m going to add “ShowFacebookLogin” and “HideFacebookLogin” animations. My login screen now looks like this (the WebBrowser will animate in when we press the button).

When we get our data back, we’re going to tell the user it worked by showing their name and their Facebook avatar. So we’ll add a Grid with an Image and a TextBlock to display the user, along with a friendly “Hello”. (Make sure to name all these things so that we can update them from the code.)
OK… out UI is simple, but ready to roll. Now let’s do something when the user clicks the sign-in button. Go to the “Click” event and add a method like “StartFacebookLogin”.

Let the User Login to Facebook
Add “using Facebook;” to your references at the top of your MainPage.xaml.cs file. Now, add the following properties:
private FacebookClient _asyncFbClient;
private string _appID = "get from your facebook app page";
private string _appSecret = "get from your facebook app page";
Now go to your StartFacebookLogin method and add the following (explained at the end).
private void StartFacebookLogin(object sender, RoutedEventArgs e)
{
string[] extendedPermissions = new[] { "user_about_me", "publish_stream" };
var oauth = new FacebookOAuthClient { AppId = _appID, AppSecret = _appSecret };
var parameters = new Dictionary<string, object>
{
{"response_type", "token"},
{"display", "touch"}
};
if (extendedPermissions != null && extendedPermissions.Length > 0)
{
var scope = new StringBuilder();
scope.Append(string.Join(",", extendedPermissions));
parameters["scope"] = scope.ToString();
}
var loginUrl = oauth.GetLoginUrl(parameters);
webBrowser.Navigated += new EventHandler<NavigationEventArgs>(CheckForAuth);
webBrowser.Navigate(loginUrl);
}
Remember how I told you to keep the Graph API open? Here is why. It has a big list of all the extendedPermissions that you can tell Facebook you want from the user. Here, we’ve asked for basic user information and the ability to publish to the user’s stream. Ask for only the permissions you need. The user can see the details of your permission request and may reject it if you ask too much.
Next, we create our OAuth client using out AppID and AppSecret and create a Dictionary of parameters communicating to Facebook the details of our request (for example, setting “display”, “touch” tells Facebook that we want the mobile interface.
We write out permission request into our parameters and then get a login url, which we will direct to our webBrowser. Here is what we will should get.

At the point Facebook walks the user through their login and, when they are done, it hands us back the access token we’ll need to get the user info and let the user make posts through our app.
This is why we attached the CheckForAuth event handler to our webBrowser. When we navigate to a new page, we’ll check to see if we got an access token using this code:
private void CheckForAuth(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult result;
if (FacebookOAuthResult.TryParse(e.Uri, out result))
{
if (result.IsSuccess)
{
IsolatedStorageSettings Settings = IsolatedStorageSettings.ApplicationSettings;
if(Settings.Contains("MyFacebookAccessToken"))
Settings["MyFacebookAccessToken"] = result.AccessToken;
else
Settings.Add("MyFacebookAccessToken", result.AccessToken);
Settings.Save();
_asyncFbClient = new FacebookClient(result.AccessToken);
_asyncFbClient.GetCompleted += new EventHandler<FacebookApiEventArgs>(_asyncFbClient_GetCompleted);
_asyncFbClient.GetAsync("/me");
}
}
}
If the Uri does contain a Facebook OAuth result and it is a success, we save the access token to our settings and then immediately use it to get the most basic user information.
The problem we have right now is that we have no class to structure the data that comes back. So get that all squared away.
First, right-click on “References” and select “Add Reference…”. Select “System.Runtime.Serialization”.
Next, add a class to your project (I added mine in a folder called “Models”) and name it FacebookUser.cs.

In that class, add the following code
[DataContractAttribute]
public class FacebookUser
{
public FacebookUser() { }
private string _id;
[DataMember(Name = "id")]
public string ID
{
get { return _id; }
set { _id = value; }
}
private string _name;
[DataMember(Name = "name")]
public string Name
{
get { return _name; }
set { _name = value; }
}
}
The sample project has a much larger (although still incomplete) version of this model. But this one will do for our purposes.
We’ll make our “GetCompleted” event handler (remember that?) look like this:
void _asyncFbClient_GetCompleted(object sender, FacebookApiEventArgs e)
{
FacebookUser _fbUser = e.GetResultData<FacebookUser>();
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
fbName.Text = _fbUser.Name;
BitmapImage bi = new BitmapImage(new Uri("https://graph.facebook.com/" + _fbUser.ID + "/picture"));
fbAvatar.Source = bi;
HideFacebookLogin.Begin();
});
_asyncFbClient.GetCompleted -= _asyncFbClient_GetCompleted;
}
What we’ve done here is shove our data into a FacebookUser model. Then we use BeginInvoke to bring ourselves back to the UI thread and set all the properties we want.
Finally, we start the animation that hides the login data and shows that our Facebook login was a success.
Boom!

January 2nd, 2012
I just spent a couple days on this and, in the end, I didn’t really figure it out. Someone else at my work (the brilliant Rylan Barnes) showed me the workaround for it.
So… you want to add a cookie to your Windows Phone 7 Silverlight HttpWebRequest. Guess what? It sucks to be you! Or, at least, it sucked to be me because I couldn’t find anything on how to do this that worked.
I was working on a project that requires the user to authenticate and, on authentication, sends back a token (unique to that user) to be attached as a cookie for further authentication. However, when I attached the cookie and made my next request, it made that request without the authorization header. Our server said “Hey, looks like you’re not authenticated, I will now forget about that last cookie because you obviously didn’t get it. Have a new one!”
First I’m going to show you things that don’t work.
Didn’t Work: Adding An Empty Cookie Container to the Request
public void DoSomeCRUD(string userName, string pass)
{
HttpWebRequest request = System.Net.HttpWebRequest.Create("https://myurl.com") as HttpWebRequest;
if (HasSavedCookieContainer)
request.CookieContainer = SavedCookieContainer();
else
request.CookieContainer = new CookieContainer();
request.Credentials = new NetworkCredential(userName, pass);
request.BeginGetResponse(new AsyncCallback(GetMyResponse), request);
}
private void GetMyResponse(IAsyncResult MyResponseAsync)
{
HttpWebRequest request = (HttpWebRequest)MyResponseAsync.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(MyResponseAsync);
// this method save the cookie container to IsolatedStorage
// so I can attach it to the request the next time I open the app.
SaveCookieContainer(request.CookieContainer);
}
The saving worked, the cookie container came back just as I saved it. And then… it didn’t work. It was as if the cookie didn’t exist.
Didn’t Work: Ripping The Token Out Of the “Set-Cookie” Header
public void DoSomeCRUD(string userName, string pass)
{
HttpWebRequest request = System.Net.HttpWebRequest.Create("https://myurl.com") as HttpWebRequest;
if (IsolatedStorageSettings.ApplicationSettings.Contains["MyToken"])
{
string myToken = (string)IsolatedStorageSettings.ApplicationSettings["MyToken"];
Cookie c = new Cookie("MyCookieName", myToken, "[valid path]", "[valid domain]");
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(new Uri("http://myurl.com"), c);
}
else
request.CookieContainer = new CookieContainer();
request.Credentials = new NetworkCredential(userName, pass);
request.BeginGetResponse(new AsyncCallback(GetMyResponse), request);
}
private void GetMyResponse(IAsyncResult MyResponseAsync)
{
HttpWebRequest request = (HttpWebRequest)MyResponseAsync.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(MyResponseAsync);
// this method looked for "Set-Cookie" information in the header
// and the pulls out the token data by brute force and save the
// token as a string
if (ResponseHasSetCookieInHeader(response))
{
string rawToken = GetTokenFromResponse(response);
IsolatedStorageSettings.ApplicationSettings["MyToken"] = rawToken;
IsolatedStorageSettings.ApplicationSettings.Save();
}
}
The save worked here too, but the same result… it was like the cookie didn’t exist.
This Worked: Adding the Cookie as a Header
Finally we added the token and the credential information as header items. This finally worked.
public void DoSomeCRUD(string userName, string pass)
{
HttpWebRequest request = System.Net.HttpWebRequest.Create("https://myurl.com") as HttpWebRequest;
if (IsolatedStorageSettings.ApplicationSettings.Contains["MyToken"])
request.Headers["Cookie"] = "MyTokenName=" + (string)IsolatedStorageSettings.ApplicationSettings["MyToken"];
request.Headers["Authentication"] = "Basic " + Convert.ToBase64String(StringToAscii(userName, pass));
request.BeginGetResponse(new AsyncCallback(GetMyResponse), request);
}
private void GetMyResponse(IAsyncResult MyResponseAsync)
{
HttpWebRequest request = (HttpWebRequest)MyResponseAsync.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(MyResponseAsync);
// this method looks for "Set-Cookie" information in the header
// and the pulls out the token data, saving it to Isolated Storage
if (ResponseHasSetCookieInHeader(response))
{
string rawToken = GetTokenFromResponse(response);
IsolatedStorageSettings.ApplicationSettings["MyToken"] = rawToken;
IsolatedStorageSettings.ApplicationSettings.Save();
}
}
For the sake of giving credit, here is the StringToAscii method for the Authentication, tweaked from this StackOverflow answer from Hans Passant
public static byte[] StringToAscii(string userName, string pass)
{
string s = userName + ":" + pass;
byte[] retval = new byte[s.Length];
for (int ix = 0; ix < s.Length; ++ix)
{
char ch = s[ix];
if (ch <= 0x7f) retval[ix] = (byte)ch;
else retval[ix] = (byte)'?';
}
return retval;
}
April 8th, 2011
UPDATE (4/9/2011) : MIX Outsider has been updated to fix some “no network” issues and refine the message creation.

MIX11 Outsider is the MIX11 app that doesn’t care about your schedule. It cares about something more important: the people you want to talk to, meet, or otherwise hang out with at MIX. Using a map of the conference floor and a simple “battleship” mapping metaphor, you can tweet, email or text your position at the conference. Don’t eat alone in awkward silence… instead find that Twitter friend who doesn’t have a clear picture of themselves in their avatar. Don’t spend half your pre-keynote time waving your hands in the air. Just tap where you are on the map and send out a link like this one.
http://mixoutsider.com/H60
And a quick video of the application in action
MIX11 Outsider Windows Phone 7 App Screencast from Matthias Shapiro on Vimeo.
I wish I could introduce this app with a bit more fanfare, but I’ve been waiting since Monday for my app to get through the submission process. I was hopeful that, if I got it in a week before MIX, I would make it in time for the conference. At the moment, that hope fades. As a result, until I can get the app into the Marketplace, it will be available here for download so Windows Phone 7 devs can sideload it onto their phones
MIX Outsider (for sideloading)
(Don’t know how to sideload an app? James Ashley has a great post on sideloading to the emulator or to a device.)
The funniest thing is that the “big idea” in this app isn’t really even the app itself. The app is really just the most complete extension of the original idea.
You see, last year at MIX 10, there was a massive coordination effort among my colleagues to try and sit together during the keynote talks. This led to e-mails, text messages, phone calls, and tweets with hard to understand directions like
“We’re 12 rows from the back in the middle of the far right side as you come in (stage left).”
But my decision to do something about it came when a friend spent 10+ minutes with his lunch plate in hand trying to find our table. I thought, “This is absurd… there must be a better way to find people.”
Unfortunately, my GPS did not work very well inside the conference… which didn’t really matter since (I assume) no one wants to open up a Google Maps or Bing Maps to find people inside a building.
So Jason Alderman and I discussed the problem and thought that it might be fun to do a “Battleship” metaphor for finding people at MIX11, laying the grid on a map of the conference floor. Based on that concept, I wrote a little application that allows user to tap to see where they are and send that information out. It then collects all the messages sent out with the app and shows them on the map with the users’ twitter avatars.
Users can send public messages using Twitter or private messages via text message or e-mail. Private messages are not broadcast and cannot be seen by anyone. They contain only the helpful link to the MIX Outsider reference website (designed by the aforementioned Jason Alderman) without any identifying information.
But my biggest hope is that this application gives people a point of reference so that even people who don’t have a Windows Phone 7 device can see the tweets, reference the website and still find the people they want to meet at MIX11.
January 17th, 2011
App bars in Windows Phone 7 are actually a pretty cool little bit of functionality. They give the user 1-4 instantly accessible options for dealing with the screen the user is on, their buttons auto-animate in, they offer “always on” funtionality that isn’t going to be hidden by the on-screen keyboard, they give designers and developers instant access to a range of default icons in Windows Phone 7 ecosystem and they offer a much wider range of options when the user taps on the ellipses to open more options.
That’s a lot for such a little thing item. So you may be asking yourself, “What the hell is he talking about? What is an ‘App Bar’?” This:

And like this when the ellipses are tapped

But what gets me is the fact that making these things is so damn easy, thanks to the fact that Blend is the single greatest product ever created for people who want to design user interfaces. And you can quote me on that. My crush on the Microsoft Blend team is well documented.
Anyway.
So let’s go about mak
Making the App Bar
ing this app bar. You may be surprised to know that we can do pretty much everything we need to do without a single line of code. Because Blend is so stinking awesome.
First, select the PhoneApplicationPage in your Object and Timeline tab in Blend.

In the “Common Properties” section, you’ll see an “ApplicationBar” property. Click on the “New” button. You should see the following:

Add App Bar Buttons
Click on the “…” button to the right of “Buttons (Collection)”. Up will pop a “Collection Editor: Buttons” pop-up. Click on the “Add another item” button.

Type “Button” and you should see a “ApplicationBarIconButton” option.

Double-click on it. It will add an App bar button to your app bar. You should have a set of “Common Properties” that you can set. Type in the text you want (in our case, “done”) and click on the IconUri box. You will see a list of default Windows Phone 7 icons. Pick the one that works for you (I picked the check mark).

Do that same thing over again, but pick the close icon and give it the text “close”. Hit “OK” to close the app bar pop-up. Believe it or not, we’re done. Yeah, we need to hook up some Click events so they can actually do something, but the rest of it is all taken care of.
If you need to get back to the App Bar design, you can just click on the ApplicationBar in the “Objects and Timeline” and see the options again.
Add App Bar Menu Items
Adding menu items is similarly easy. Under the “Buttons (Collection)” item we clicked on earlier, there is a “MenuItems (Colleciton)” button. Click on it.

We see the same “Collection Editor and we’ll click “Add another item” again. This time, though, we type “menu” and double click on ApplicationBarMenuItem.

Add the text (“do one thing”) and run the process again to add another item. Click “OK” when you’re done.
Colors & the Application Bar
Designing the App Bar is pretty easy. The icons that we assigned to the buttons actually just act as opacity masks (I assume that’s how it works… it seems to make sense) so that they will change to whatever color is assigned to the foreground of the app bar. Warning: they will default to the theme foreground unless you explicitly set them to be another color. If you’ve decided not to work with the default theming engine, you will need to explicitly set the foreground and the background of the App Bar.
I talk about this a little bit more in my post on Windows Phone 7 theming. That might be a good place to go if you’re working on fine-tuning the app bar to fit into a non-themed design.
January 17th, 2011
Let’s say you don’t really want to play nice with the theming engine in Windows Phone 7. This would be pretty understandable… when you play nice with theming you either need to 1) come up with some nice innovative solution that detects themes and sets brushes and colors dynamically or 2) use only the black, white, gray and accent colors that Windows Phone 7 theming gives you by default.
If you want to create a design that uses some custom colors, it can be difficult to make sure those colors fit both themes, which can throw a cramp into your creative juices. Additionally, if you decide to toss theme-compatibility to the wind in favor of your own design, you’ll need to make sure all your control templates conform and don’t go all wonky when the user changes their theme.
This can be a pain.
To help in this endeavor, I would like to present two resource dictionaries and a sample project.
DarkStyles.xamly – rename to DarkStyles.xaml (irritating download issue)
LightStyles.xamly – rename to LightStyles.xaml (irritating download issue)
Theme Resistant Sample Project
The basic idea is that I found the source style resource dictionary for all the Windows Phone 7 controls. These styles are implicitly set by the system depending on the users’ settings. We can override these settings with our own local resources. So all we need to so is set either point to the LightStyles.xaml or the DarkStyles.xaml as resource dictionaries in the App.xaml and all the controls will ignore the system settings and conform to our defined settings. Another bonus is that you can use take these dictionaries and use them to play around with colors to see how a solid theme is built in Silverlight.
So, let’s quickly walk through the process of forcing a theme in your project.
First, use Blend. It’s awesome. (You could probably use Visual Studio too, I guess.)
In your project, if you don’t have a “Resources” folder, right-click on your project and create that folder.’

Now right click on your Resources folder and “Add An Existing Item…”. In the resulting pop-up navigate to either the DarkStyles.xaml or the LightStyles.xaml file.

This should add the necessary code auto-magically into your App.xaml, but double check. You should see something like this:

And that’s it! Sort of. I want to make note of a couple of clean-up issues.
Use Blend To Check Themes
First of all, you should know how to quickly test theming changes in Blend. In the top left-hand corner, you should see a set of tabs that say “Parts”, “Projects”, “Assets” etc. If it doesn’t say “Devices”, go to the menu bar and select “Window –> Device”. This will bring up a tab that looks like this:

From here you can change the theme and accent on the fly and see the changes in your design without running the app.
HOWEVER!
Some things don’t show up very well in the Blend theming, so always always always test your app on the emulator or on the phone.
Set Your Root Background
One of those things is that the default status for a PhoneApplicationPage is to have a transparent background. You’ll want to make sure that the LayoutRoot Grid (or layout element) in your application has the background set to “PhoneBackgroundBrush”.

Turn Off Your System Tray (Maybe)
Next, you might want to turn off the System Tray at the top of your app. That’s this thing

You have no control over what color it is, only whether or not it can be seen. Select the PhoneApplicationPage in your “Objects and Timeline” tab and uncheck the “Show SystemTray”. This is not a must (most apps will still look fine with the SystemTray on) but it’s something to think about

Set The Colors On Your App Bar
Finally, if you have an Application Bar in your screen, you’ll want to make sure the colors are explicitly set on those. (Don’t know how to make an application bar? Check this post out.) Select the ApplicationBar in your “Objects and Timeline”. Now click on the little box next to the BackgroundColor property and select “Local Resources –> PhoneChromeColor”.

Similarly, set the ForegroundColor to “LocalResources –> PhoneForegroundColor”.You’re all set… you now have a theme-proof application.
January 10th, 2011
Normally, I wouldn’t blog something that seems obvious, but it took me hours to figure this out and I always try to write blog posts for stuff that it took me a long time to figure out. Enormous props to Walt Ritscher (Twitter: @waltritscher) who helped me figure this out.
This blog post is for you if you have a sound file and you want it to:
- be included with the application when the user downloads the app
- play no matter what… even if the user is listening to music
First, grab the audio you want to add to the application and, if it’s not already a .wav file, make it so. If you’re just trying this out for kicks (or for the learning experience), download this files.
Coyote.wav
When prepping your audio, keep in mind if you want the user to hear it over their music. If so, make sure it is LOUD. I spent almost an hour thinking this method didn’t work because I couldn’t hear the sound over my music.
Next, create a directory in your Windows Phone 7 project and add your audio file like so:

Then select your audio file and change the “Build Action” to “Resource”

Now right-click on the “References” in your project and click “Add Reference…”. Find the “Microsoft.Xna.Framework” reference and add it to your project.


To the top of your class, add:
using Microsoft.Xna.Framework;
Now we’re going to create a stream from that resource and use that stream to play our sound.
StreamResourceInfo streamInfo = Application.GetResourceStream(
new Uri("/MyProjectName;component/Sound/Coyote.wav",
UriKind.Relative));
SoundEffect se = SoundEffect.FromStream(streamInfo.Stream);
SoundEffectInstance soundInstance = se.CreateInstance();
soundInstance.Play();
And that’s it. Your sound should play.
If you’re reading this, I assume you’re working with sound in some capacity. If you’re new to the work of sound and just want a simple way to edit and export sound files for your app, I highly recommend the free sound editing application Audacity. It saved me on my current project.
If you’re using Audacity and editing/creating sounds to hear while music is running, take whatever sound you have and amp up the gain so that the volume is peaking at about 0.

This sounds extreme, but it’s the only way I’ve been able to get the sounds to reliably make themselves heard over rock music.
I also recommend checking out Jaime Rodriguez’s post on running a Windows Phone app under the lock screen. That way you can play sounds even if the user allows the phone to lock itself.
November 30th, 2010
I’m working on a new project in which I need multiple ListPickers in a ScrollViewer.
The ListPicker is available via the Silverlight Toolkit for Windows Phone 7. If you don’t have it, you should get it. Get the source as well, for reasons that will be clear in one more sentence.
The only problem is that I can’t scroll if I do this because I run the risk of accidentally opening the ListPicker (which should be a tap interaction) when swiping (which is a gesture interaction):
I posted this as a work item on codeplex, so it will probably be fixed in a couple months (sometime in early 2011), but if you’re having a problem with it, do the following:
Open up the source, go to the Microsoft.Phone.Controls.Toolkit project, the ListPicker folder and open the ListPicker.cs file. Go down to the OnManipulationCompleted event and after the line
base.OnManipulationCompleted(e);
add the following conditional for the rest of the code in the method:
if ((Math.Abs(e.TotalManipulation.Translation.X) < 20) && (Math.Abs(e.TotalManipulation.Translation.Y) < 20)){
[Other code]
}
This catches manipulations that are less tap-y and more scroll-y and lets them slide by without opening the ListPicker. If you wanted to be really careful, you could probably change the conditional to 10 or even 5. Most of the taps I checked had pretty small (single digit) manipulation deltas.
November 30th, 2010
One of the things that I’m fascinated with is trying to deconstruct the motion design in Windows Phone 7. I actually came to software design out of multimedia production so I’ve always loved animations in UI design. At some point, I hope to do a series of posts overall on motion design in Windows Phone 7. Actually, I really want to do a talk about Windows Phone 7 motion design at MIX 11. Take note, powers that be.
Anyway, the first step is to get some solid video of the WP7 motion so that I can look at it closely. After 3 cameras and testing a couple different lenses, I got what I think is pretty decent video. Eventually, I’d like to pair these with the XAML necessary to recreate them, but for now I hope it helps someone.
Also, now that I’ve got this process down, if you want video of a particular animation, let me know and I’ll make it happen. Make sure you tell me exactly how to get the animation you want or I might focus on the wrong thing.
E-Mail
Animations: List Item-to-detail animation
Download higher resolution video
Video of e-mail program in Windows Phone 7 from Matthias Shapiro on Vimeo.
Marketplace
Animations: dynamic Button animation, Panorama animation, List Item-to-detail animation
Download higher resolution video
Video of Marketplace App in Windows Phone 7 for motion study from Matthias Shapiro on Vimeo.
Messaging
Animations: List Item-to-Detail animation, cascading list item swivel (in and out), main screen selection animation
Download higher resolution video
Video of Messaging Motion in Windows Phone 7 for motion study from Matthias Shapiro on Vimeo.
Main Screen
Animations: Main screen-to-application list animation
Download higher resolution video
Untitled from Matthias Shapiro on Vimeo.
Main Screen
Animations: Main Screen load in animation, application selected animation
Download higher resolution video
Opening and closing applications in Windows Phone 7 (for motion study) from Matthias Shapiro on Vimeo.
November 16th, 2010
Click here if you don’t want to hear me complain about the Silverlight toolkit and you just want to get to the animations.
If you are like me, you’re working on Windows Phone 7 applications in your pajamas, subsisting on pork jerky and Coke Zero and dreaming of that one project that will make you richer than your wildest dreams while begging Dell to actually announce some kind of release date for the Dell Venue Pro.
But I suspect that we have less in common. In fact, the only thing we probably have in common is a desire to know how to actually replicate the Windows Phone 7 motion design.
That and our breathtaking good looks.
But back to the motion design. If you download the Silverlight Windows Phone toolkit source code, download and run it, you’ll see some animations that look kind of like the animations on the phone but not really. There are a couple of reasons for this.
Reason #1 – The easing functions have been placed on the wrong keyframes in the toolkit. They should be placed on the second keyframe, but they are on the first keyframe. This, of course, doesn’t make any sense since there is nothing to ease in the first keyframe, so I suspect it is some kind of transcription error.
Reason #2 – The easing function is an exponential one. Not a problem, pretty normal. But its exponent is 15. To give you a good idea of what that kind of “easing” looks like, here is the Blend representation of an exponent 15 easing:

It’s basically like cutting the animation time by two thirds. In contrast, here is the function with an exponent 5 easing:

Much ease-ier (get it?).
OK… enough about the Silverlight toolkit. You want to actually know how to write animations that approximate Windows Phone 7, right?
I currently have no phone, so I can’t study the animations in the closest detail (waiting for the Dell Venue Pro), but here is what I’ve gathered from the Silverlight toolkit and what I can see in the emulator:
“In” animations
When some UI component is appearing, we would use an “In” animation. “In” animations are a shade longer than “Out” animations. I assume this is to help the users’ eyes adjust to the new UI.
To the best of my knowledge, “In” animations:
- are .35 seconds long
- use exponential 5 easing
“Out” animations
When a UI component is exiting (either through navigation or due to the lack of need for it) we use an “Out” animation. Their shorter length leave the user with the impression of speed when they want to get to the next UI.
“Out” animations:
- are .25 seconds long
- use exponential 5 easing
OK… now on to some XAML:
Turnstile Animations:
This is when the screen-wide UI turns on its left-hand edge, such as when the user opens an application.
Turnstile Forward In
Turnstile Forward In
- <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty=”(UIElement.Projection).(PlaneProjection.RotationY)”>
- <EasingDoubleKeyFrame KeyTime=”0″ Value=”-80″ />
- <EasingDoubleKeyFrame KeyTime=”0:0:0.35″ Value=”0″>
- <EasingDoubleKeyFrame.EasingFunction>
- <ExponentialEase EasingMode=”EaseOut” Exponent=”5″/>
- </EasingDoubleKeyFrame.EasingFunction>
- </EasingDoubleKeyFrame>
- </DoubleAnimationUsingKeyFrames>
Turnstile Forward Out
Turnstile Forward Out
- <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty=”(UIElement.Projection).(PlaneProjection.RotationY)”>
- <EasingDoubleKeyFrame KeyTime=”0″ Value=”0″ />
- <EasingDoubleKeyFrame KeyTime=”0:0:0.25″ Value=”50″>
- <EasingDoubleKeyFrame.EasingFunction>
- <ExponentialEase EasingMode=”EaseIn” Exponent=”5″/>
- </EasingDoubleKeyFrame.EasingFunction>
- </EasingDoubleKeyFrame>
- </DoubleAnimationUsingKeyFrames>
Turnstile Backward In
Turnstile Backward In
- <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty=”(UIElement.Projection).(PlaneProjection.RotationY)”>
- <EasingDoubleKeyFrame KeyTime=”0″ Value=”50″ />
- <EasingDoubleKeyFrame KeyTime=”0:0:0.35″ Value=”0″>
- <EasingDoubleKeyFrame.EasingFunction>
- <ExponentialEase EasingMode=”EaseOut” Exponent=”5″/>
- </EasingDoubleKeyFrame.EasingFunction>
- </EasingDoubleKeyFrame>
- </DoubleAnimationUsingKeyFrames>
Turnstile Backward Out
Code Snippet
- <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty=”(UIElement.Projection).(PlaneProjection.RotationY)”>
- <EasingDoubleKeyFrame KeyTime=”0″ Value=”0″ />
- <EasingDoubleKeyFrame KeyTime=”0:0:0.25″ Value=”-80″>
- <EasingDoubleKeyFrame.EasingFunction>
- <ExponentialEase EasingMode=”EaseIn” Exponent=”5″/>
- </EasingDoubleKeyFrame.EasingFunction>
- </EasingDoubleKeyFrame>
- </DoubleAnimationUsingKeyFrames>
Slide Animations
We see these animations in things like creating new e-mails. They seem to be used when the user is doing some task that fits within the context of the screen they are already on. Slide animations use an opacity animation combined with a horizontal or vertical animation.
Slide animations use the same .25 seconds on animate out and .35 seconds on animate in and, according to the toolkit, the UI slides 200 pixels in whatever direction it is sliding.
Here is a sample Slide Up and Slide Down animation:
Slide Up Fade In animation
Slide Up Fade In
- <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty=”(UIElement.RenderTransform).(TranslateTransform.Y)”>
- <EasingDoubleKeyFrame KeyTime=”0″ Value=”200″ />
- <EasingDoubleKeyFrame KeyTime=”0:0:0.35″ Value=”0″>
- <EasingDoubleKeyFrame.EasingFunction>
- <ExponentialEase EasingMode=”EaseOut” Exponent=”5″/>
- </EasingDoubleKeyFrame.EasingFunction>
- </EasingDoubleKeyFrame>
- </DoubleAnimationUsingKeyFrames>
- <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty=”(UIElement.Opacity)”>
- <EasingDoubleKeyFrame KeyTime=”0″ Value=”0″ />
- <EasingDoubleKeyFrame KeyTime=”0:0:0.35″ Value=”1″>
- <EasingDoubleKeyFrame.EasingFunction>
- <ExponentialEase EasingMode=”EaseOut” Exponent=”5″/>
- </EasingDoubleKeyFrame.EasingFunction>
- </EasingDoubleKeyFrame>
- </DoubleAnimationUsingKeyFrames>
Slide Down Fade Our animation
Code Snippet
- <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty=”(UIElement.RenderTransform).(TranslateTransform.Y)”>
- <EasingDoubleKeyFrame KeyTime=”0″ Value=”0″ />
- <EasingDoubleKeyFrame KeyTime=”0:0:0.25″ Value=”200″>
- <EasingDoubleKeyFrame.EasingFunction>
- <ExponentialEase EasingMode=”EaseOut” Exponent=”5″/>
- </EasingDoubleKeyFrame.EasingFunction>
- </EasingDoubleKeyFrame>
- </DoubleAnimationUsingKeyFrames>
- <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty=”(UIElement.Opacity)”>
- <EasingDoubleKeyFrame KeyTime=”0″ Value=”1″ />
- <EasingDoubleKeyFrame KeyTime=”0:0:0.25″ Value=”0″>
- <EasingDoubleKeyFrame.EasingFunction>
- <ExponentialEase EasingMode=”EaseOut” Exponent=”5″/>
- </EasingDoubleKeyFrame.EasingFunction>
- </EasingDoubleKeyFrame>
- </DoubleAnimationUsingKeyFrames>
Coming soon… swivel animations and rotate animations… I’m not totally certain on what I’m seeing in the toolkit. It doesn’t seem to jive with what I’m seeing from the phone. I may wait a few days until I get a phone and can dissect the motion design a little bit more closely.
June 28th, 2010
I’m currently working on porting the run-away hit mobile application ShopSavvy to Windows Phone 7 (sign up to be a beta tester) and one of the things I really wished I had was the WrapPanel.
(For those who are new to Silverlight/WPF/Windows Phone 7, the WrapPanel stacks UI elements either horizontally or vertically like the StackPanel except that, when it hits the panel limit it… wait for it… wraps and starts stacking in a new column/row. Handy.)
I found a way to add it with the Silverlight Toolkit, but doing that added 140 Kb to my application. Maybe I’m just stuck in the world of J2ME, but adding 140 Kb to my mobile app isn’t OK if I can help it. I found this post from Jeff Wilcox on adding the WrapPanel and that didn’t seem to work for me. (My comments are the whiny ones at the end of the post.)
But I finally got it working and I’ll tell you how.
Or I could just taunt you. That would be fun too.
Naw, I’m just kidding. Here’s the stuff you need.
Windows Phone 7 WrapPanel and DockPanel (Source)
Windows Phone 7 WrapPanel and DockPanel (DLL)
All you have to do is download the DLL, unzip and reference in your app like so:
Right click on the “References” section of your project.
Select the WP7Panels DLL from whatever folder you put it in and see it show up in your References

Open up the “Assets” section and type “wrap” or “dock” the wrap-or-dock panel should show up. Double click it or drag it onto the canvas to add it to your app. Blend will take care of the rest of the namespaces and everything.
And start adding items to your panel. It should work the way it’s supposed to work.

One note with the DockPanel… items placed in the DockPanel need to have the attached property
[xmlns]:DockPanel.Dock=”[something]”
if you want them to do something other than align in the center. The [xmlns] name should be the same thing that is before the “DockPanel” in the XAML. It will most likely be “WP7Panels”. Therefore, the following XAML:
<WP7Panels:DockPanel>
<Button Content="Button" WP7Panels:DockPanel.Dock="Bottom" />
<Button Content="Button" WP7Panels:DockPanel.Dock="Top" />
<Button Content="Button" WP7Panels:DockPanel.Dock="Right" />
<Button Content="Button" WP7Panels:DockPanel.Dock="Left" />
<Button Content="Button" />
</WP7Panels:DockPanel>
…should look like this:
If you want to add the actual files to your Windows Phone 7 app instead of just referencing the DLL (perhaps you are crazy or you have a deep and desperate need to fully understand absolutely everything you touch or you are a C++ developer), you can download the source. I’ve consolidated the DockPanel code into a single file (DockPanel.cs), but you’ll need the following files to get the WrapPanel working (all included in the source).
- LengthConverter.cs
- NumericalExtensions.cs
- OrientedSize.cs
- TypeConverter.cs
- WrapPanel.cs
Finally, if you need something else for Windows Phone 7 from the Silverlight Toolkit, you can either add the entire toolkit (explained here) or download the source for the latest Silverlight 3 build and open it in Visual Studio 2010 (for some reason, I couldn’t get it to open in Visual Studio 2008). It should update and you should be all set playing around in there to extract the stuff you need.
Good luck!