Windows Phone Application Bar Icons: Gotcha

I wanted to toggle my Panzer General game between air and ground mode. To do so, I created an Icon Button like so:

1 <shell:ApplicationBarIconButton x:Name="airSurface" Text="air/surface" IconUri="Images/appbar.upload.rest.png" Click="airSurface_Click" />

I then wired up the code-behind like so:

1 if (Game.InGroundMode) 2 { 3 this.airSurface.IconUri = new Uri(@"/Images/appbar.upload.rest.png", UriKind.Relative); 4 Game.InGroundMode = false; 5 } 6 else 7 { 8 this.airSurface.IconUri = new Uri(@"/Images/appbar.download.rest.png", UriKind.Relative); 9 Game.InGroundMode = true; 10 } 11

When I ran it, I got this:

image

I first thought – I must have the url wrong. I double checked the properties of the icon images – they are content. After screwing around with url and paths for a bit, it dawned on me that perhaps the uri was fine. Sure enough, when I separated the uri creation into its own line, the error was on the IconUri assignment – the button is null! For someone used to WinForms/WebForm programming, this was unexpected.

image

Jumping back to Nathan’s excellent book, I see that he has a different way of referring to IconButtons in code. I updated my code to this:

1 IApplicationBarIconButton button = sender as IApplicationBarIconButton; 2 3 if (Game.InGroundMode) 4 { 5 Uri uri = new Uri(@"/Images/appbar.upload.rest.png", UriKind.Relative); 6 button.IconUri = uri; 7 Game.InGroundMode = false; 8 } 9 else 10 { 11 button.IconUri = new Uri(@"/Images/appbar.download.rest.png", UriKind.Relative); 12 Game.InGroundMode = true; 13 } 14

And it now toggles as expected

So the two lessons are:

1) When 1 line of code does the work on two, you are setting yourself up for debugging headaches. Separate 1st, then consolidate

2) Just b/c it looks like a duck, walks like a duck, and quacks like a duck; it doesn’t mean that it follows the other APIs that you are used to….

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: