Thursday, 31 March 2011

Changing ApplicationBar items at runtime on Windows Phone 7

I'm currently developing a Windows Phone 7 application for work (that adds to the list of languages I've worked on since joining 6 months ago, the others being python and java - gotta love the labs environment!)

Something small which vexed me briefly was trying to change icons and menu bar items at runtime. If you've tried to reference them by name in code then you'll have most likely been presented with a null reference error.

The trick is to reference them by index number (zero based), for example:

var iconbutt = (IApplicationBarIconButton)ApplicationBar.Buttons[0];
var menuitem = (IApplicationBarMenuItem)ApplicationBar.MenuItems[0];

You can then modify them as required.

The reason that you have to do this is because the ApplicationBar and it's child items stem from Microsoft.Phone.Shell namespace rather than System.Windows.Controls. This also explains why you can't simply data bind, although there are workarounds for that.