How to localize the text of each button of the ApplicationBar?

In general you can provide, in your solution, several AppResource files, a default one (AppResource.resx) and one for each language you like to support (es. AppResource.en-EN.resx, AppResource.it-IT.resx, AppResources.es-ES.resx): the default one will be used for all the other languages not explicitly listed.

As clearly stated in an MSDN page, it is not sufficient to include that AppResource files, but you have also to declare the supported cultures in the .csproj of the UI project (and possibly all the others that may needs to use language specific strings): to do that you need to “close the project and open the project file (<project name>.csproj) in a text editor. Locate the <SupportedCultures> tag and add the names of each additional culture (language) your application needs to support. You should have an entry for each .resx file added to the project). Separate the language names using a semicolon, and only add the additional culture names. For example, if an application uses English (United States) for its default culture, but the application also supports German (Germany) and Spanish (Spain), you would update this tag as follows:

<SupportedCultures>de-DE;es-ES;</SupportedCultures>

Then, everytime you have to write a string to the UI, you must get the proper string from those dictionaries: the operating sytem automatically chooses the proper language depending to the one configured in the PDA.

For convenience, I use the following utility class to access the resource strings:

    /// <summary>
    /// Classe utilizzata per esporre le risorse presenti in AppResource.resx; Nota che Visual Studio quando si crea quel file genera già una classe AppResource.cs che contiene quei dati.
    /// Questa classe wrappa proprio quella classe AppResource
    /// </summary>
    public class LocalizedStrings {
        // Per Silverlight - XAML: per recuperare le risorse nella pagina XAML
        private static AppResource localizedResources = new AppResource(); //proprietà che restituisce prorio una classe AppResources
        public AppResource LocalizedResources { //era public
            get { 
                return localizedResources;
            }
        }

        // Shortcut to Resource Manager: : per recuperare le risorse nella pagina C#
        public static String GetString(String resourceKey) {
            return AppResource.ResourceManager.GetString(resourceKey);
        }
    }

Then from your C# code you can get a string in this way:

MessageBox.Show(sbErrorMessage.ToString(), LocalizedStrings.GetString("ExceptionCaption"), MessageBoxButton.OK);

and in the xaml you can use the following:

<TextBlock Text="{Binding LocalizedResources.User, Source={StaticResource LocalizedStrings}}">

Now, what about the text associated to each button of the ApplicationBar?
When you create a new page with Visual Studio, at the end of the xaml file there is already a commented part related to the creation of some ApplicationBar:

    <!--Sample code showing usage of ApplicationBar-->
    <!--<phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
            <shell:ApplicationBarIconButton x:Name="appbar_button1" IconUri="/Resources/Images/Icons/ApplicationBar/dark/appbar.button1.png" Text="Button 1" Click="AppBarSelectButtonClick"/>
            <shell:ApplicationBarIconButton x:Name="appbar_button2" IconUri="/Resources/Images/Icons/ApplicationBar/dark/appbar.button2.png" Text="Button 2" Click="AppBarSelectButtonClick"/>
            <shell:ApplicationBar.MenuItems>
                  <shell:ApplicationBarMenuItem Text="MenuItem 1"/>
                  <shell:ApplicationBarMenuItem Text="MenuItem 2"/>
            </shell:ApplicationBar.MenuItems> 
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>-->

However if you use that code, you hardwire the text associated to each button and, because the ApplicationBar is not a silverlight component, it is NOT possible to handle localization in the following way, as you perhaps expected:

<!-- IT DOESN'T WORK -->
<shell:ApplicationBarIconButton x:Name="appButtonCancel" IconUri="/Resources/ApplicationBar/dark/appbar.cancel.png" Text="{Binding LocalizedResources.Reset, Source={StaticResource LocalizedStrings}}" Click="appButtonCancel_Click" />

So you have are several possibilities if you want to take care of the localization but all require to add code in C#.
One way is to create to create all by code (no tags in xaml related to ApplicationBar) and add, for example in the constructor, the following code:

ApplicationBar = new ApplicationBar();
var appBarOkButton = new ApplicationBarIconButton(new Uri("/Resources/ApplicationBar/dark/appbar.check.png", UriKind.Relative));
appBarOkButton.Text = LocalizedStrings.GetString("Ok");
ApplicationBar.Buttons.Add(appBarOkButton);
appBarOkButton.Click += new EventHandler(appButtonOk_Click);
var appBarResetButton = new ApplicationBarIconButton(new Uri("/Resources/ApplicationBar/dark/appbar.cancel.png", UriKind.Relative));
appBarResetButton.Text = LocalizedStrings.GetString("Reset");
ApplicationBar.Buttons.Add(appBarResetButton);
appBarResetButton.Click += new EventHandler(appButtonCancel_Click);
ApplicationBar.IsVisible = true;

Or you can leave in the xaml the tag related to creation of the ApplicationBar, but create each button in C# code-behind.
A utility class can be used to make the code more flexible and reusable in differnt cases where you could need to add/remove ApplicationBar buttons runtime (es. depending from the shown pivot item):

<phone:PhoneApplicationPage.ApplicationBar>
<shell:ApplicationBar IsMenuEnabled="False" IsVisible="True">
<!--<shell:ApplicationBarIconButton x:Name="AllowButton" Text="si"  IconUri="/Resources/Images/Icons/ApplicationBar/dark/appbar.check.png" Click="AllowButton_Click" />
<shell:ApplicationBarIconButton x:Name="DenyButton" Text="no"  IconUri="/Resources/Images/Icons/ApplicationBar/dark/appbar.cancel.png" Click="DenyButton_Click" />-->
</shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>
Utility.UpdateAppbarButton(ApplicationBar.Buttons, 0,"/Resources/ApplicationBar/dark/appbar.check.png", LocalizedStrings.GetString("Allow"), true, new EventHandler(AllowButton_Click));           Utility.UpdateAppbarButton(ApplicationBar.Buttons, 1, "/Resources/ApplicationBar/dark/appbar.cancel.png", LocalizedStrings.GetString("Deny"), true, new EventHandler(DenyButton_Click));

where:

        /// <summary>
        /// http://stackoverflow.com/questions/4234202/hide-application-bar-icon-programmatically-in-a-wp7-silverlight-application
        /// instead of setting a button visible or not, you have to remove the button (if it's there) or re-add it if it's not.
        /// </summary>
        /// <param name="applicationBarButtons">ApplicationBar.Buttons</param>
        /// <param name="index"></param>
        /// <param name="uriString"></param>
        /// <param name="text"></param>
        /// <param name="visibility"></param>
        /// <param name="handler"></param>
        /// <returns>Restituisce la ApplicationBar.Buttons modificata</returns>
        public static IList UpdateAppbarButton(IList applicationBarButtons, int index, string uriString, string text, bool visibility, EventHandler handler) {
            ApplicationBarIconButton button1 = null;

            if (applicationBarButtons.Count > index) {
                button1 = applicationBarButtons[index] as ApplicationBarIconButton;
            }

            if (button1 != null) {
                applicationBarButtons.Remove(button1);
            }
            if (visibility) {
                button1 = new ApplicationBarIconButton(new Uri(uriString, UriKind.Relative));
                button1.Text = text;
                button1.Click += handler;
                applicationBarButtons.Insert(index, button1);
            }
            //TODO verificare se passando il puntatore, non ci sia necessità di ritornare applicationBarButtons che è già stato modificato
            return applicationBarButtons;
        }
Annunci

Informazioni su Enzo Contini

Electronic engineer
Questa voce è stata pubblicata in Windows Phone/Mobile. Contrassegna il permalink.

Una risposta a How to localize the text of each button of the ApplicationBar?

  1. essatrout ha detto:

    I would suggest you do the same as I do, use this online localization tool: https://poeditor.com/. Itțs perfect for every aspect of localization in apps and it works really simple.

Lascia un Commento/Leave a comment

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...