Tuesday, June 14, 2011

Localizing Windows Phone 7 ApplicationBar

In order to provide a seamless user experience on your Windows Phone 7 you also have to localize the ApplicationBar within your app.

First, you will encounter that the ApplicationBar on the Microsoft.Phone.Shell namespace is not an usual UIElement and therefore can not be named via
The second thing you will recognize is that the ApplicationBar property of an PhoneApplicationPage is not initialized due the usual InitializeComponent method.

On my search over the internet I spotted some suggested hints, but often the solution is obvious.
I spotted out the DependencyProperty field ApplicationBarProperty. With an simple call to
we get the ApplicationBar of the current page so that we can initialize the page property within the constructor for example:
ApplicationBar = GetValue(ApplicationBarProperty) as Microsoft.Phone.Shell.ApplicationBar
This is the first thing todo to localize the ApplicationBar.

Next you have to set the Text properties of the buttons and menu items by
((ApplicationBarIconButton)ApplicationBar.Buttons[0]).Text = LocalizedStrings.ButtonText;
((ApplicationBarMenuItem)applicationBar.MenuItems[0]).Text = LocalitedStrings.MenuItemText;
I encapsuled this within a reuseable LocalizingHelper class like this:
using System;
using Microsoft.Phone.Shell;

namespace ToBaer.CS.WP
   public static class LocalizationHelper
      public static void Localize(IApplicationBar applicationBar, string[] buttonStrings, string[] menuItemStrings)
         if (applicationBar == null)
         if (buttonStrings != null)
            SetButtonTexts(applicationBar, buttonStrings);
         if (menuItemStrings != null)
            SetMenuItemTexts(applicationBar, menuItemStrings);
      private static void SetMenuItemTexts(IApplicationBar applicationBar, string[] menuItemStrings)
         for (var idx = 0; idx < applicationBar.MenuItems.Count && idx < menuItemStrings.Length; idx++)
            if (!String.IsNullOrEmpty(menuItemStrings[idx]))
               ((ApplicationBarMenuItem)applicationBar.MenuItems[idx]).Text = menuItemStrings[idx];
      private static void SetButtonTexts(IApplicationBar applicationBar, string[] buttonStrings)
         for (var idx = 0; idx < applicationBar.Buttons.Count && idx < buttonStrings.Length; idx++)
            if (!String.IsNullOrEmpty(buttonStrings[idx]))
               ((ApplicationBarIconButton)applicationBar.Buttons[idx]).Text = buttonStrings[idx];

No comments:

Post a Comment