Skip to content

Localize a Windows Phone 7 Application

October 17, 2010

Here’s a quick guide to add content localization in your Silverlight-based Windows Phone 7 application plus a bonus dynamic way to do it (read the official documentation to get the fine prints).

First add a resource file (.resx) for each language you want to support. Here we have the default one (English) and the same filename for French  labels except the .fr suffix.

solution explorer

Don’t forget to choose “public” as the class visibility level (for the binding).

Resources settings

Unload your project and edit the csproj file to add your supported language:

CsProj

(Here the “fr” works for all regions below the “fr” culture: fr-FR, fr-CA etc.)

In the properties of your project add your default culture:

Default Language

Now add a class  (LabelsManager) to be the middle-man between the XAML and the resources files. We can’t use  directly the generated class because you need a class with a default constructor to be able to use it in the XAML.

public class LabelsManager {
     public Labels Labels { get; set; }
     public LabelsManager()
     {
        Labels = new Labels();
     }
}

Add an instance of the class as a resource in the application (App.xaml):

<Application.Resources>
     <Resources:LabelsManager x:Key="LabelsManager" />
</Application.Resources>

Now you can bind the Text Property of your TextBlock controls to your resources (see the blog of Karl Shifflet for the code of the manager class):

<TextBlock TextWrapping="Wrap" x:Name="PageTitle" Text="{Binding Source={StaticResource LabelsManager},Path=Labels.Title, Mode=OneTime}" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>

If you change the language of the emulator and restart it,you will see that the label gets the correct value :

en

params

fr

Now if you want a way to dynamically change the culture and therefore the UI you need a a little more sophisticated Manager class. First the OneTime binding can’t be used anymore since we want something dynamic. Second the manager class needs to implement the famous INotifyPropertyChanged interface. So here’s the code of the new class:

 
public class LabelsManagerDynamic : INotifyPropertyChanged
{
	private Labels labels;

	public Labels Labels
	{
		get { return labels; }           
	}

	public LabelsManagerDynamic()
	{
		labels = new Labels();
	}

	public void ResetResources()
	{
		OnPropertyChanged(() => Labels);
	}


	#region INotifyPropertyChanged region
	(...)
	#endregion
}

In the Main class if we want to change the current culture we need to: change it in the current thread and somehow warn Silverlight that something changed with the PropertyChanged event:

 
private void EnglishBt_Click(object sender, RoutedEventArgs e)
{
	Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
	Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
	ResetResources();
}

private void ResetResources()
{
	((LabelsManagerDynamic)App.Current.Resources["LabelsManagerDynamic"]).ResetResources();
}

The chain of events goes like this : first execution (en) => click on the button => change UI Culture => call ResetResources method on the Manager class => Raised PropertyChanged event => Silverlight re-binds the property and calls the getter on the Labels property and gets the French version of the resources.

dynamic

I used this post from Tim Heuer for the dynamic version.

Here’s the source code of the project on GitHub.


About these ads
22 Comments leave one →
  1. Martijn permalink
    February 12, 2011 4:10 pm

    Hi Matthieu,

    I am trying out your code, but pushing one of the buttons doesn´t seem to change a thing both in the emulator as on a device (Omnia 7) . Is the code broken, or am i missing something? Please let me know, all the best!

    Martijn

    • February 12, 2011 4:19 pm

      Hello Martijn,

      Yes the dynamic version is commented. Look at the MainPage.xaml file, line 28. Commented out this line and comment the line 25 to have only the dynamic version.

      Matthieu

  2. Martijn permalink
    February 13, 2011 7:38 am

    Hi Matthieu,

    Thank you for your swift response, you are totally right :) The routine works wonders right now and i have integrated it in my Apps Het Verkeer and Het Weer, they should show up in the marketplace later this week :) Have fun, i’ll keep an eye on your blog!

    All the best, Martijn

  3. March 11, 2011 7:27 am

    For me this sample application don’t work – the textblock is still in english.

    • March 11, 2011 10:02 am

      Hello,

      It’s because the automatic version is disabled, you need to comment out the line in the XAML file to get the textbox with binding and not the static one.

      Matthieu

      • siva permalink
        May 23, 2012 2:18 am

        hi i am also facing above same problem.even i change the language to fr .it is still in english.how to rectify that.where i need to modify to get in fr

      • May 23, 2012 8:58 am

        You need to comment out the textbox using the automatic localization.

  4. Sky permalink
    August 21, 2011 4:04 pm

    Hey there,
    just a question from total newbie:

    When I paste the Resources:LabelsManager into App.xaml I have error:
    ‘Resources’ is an undeclared prefix.

    I also hadn’t got any Resources directory made when going through Add->New item->resource file. Manually creating this directory and putting files there doesn’t help.

    What am I doing wrong?

    • Sky permalink
      August 25, 2011 3:12 pm

      Ok, I figured it out.

      In App.xaml application tag add:
      xmlns:Resources=”clr-namespace:SampleLocalization.Resources”

      and the prefix is declared :)

  5. March 2, 2012 5:29 am

    Nice post!

    Just wondering how can I set the bindings using Expression Blend.

    Thanks.

    • March 2, 2012 8:41 am

      Hello Azubi, Thanks but I’m not using Blend so I’m not sure if I can be of any help.

  6. Deluxe permalink
    April 15, 2012 4:19 pm

    Hello,

    thank you for this great tutorial. I’ve tried it and it works great!

    But I have one simple question:

    Hmm.. it’s hard to explain for me but how can I change a binding to another one by pressing a button?

    I’ve tried for example this code:

    toggleSwitch1.Content = “{Binding Source={StaticResource LabelsManager}, Path=Labels.Text1}”

    This is not working. If I click the button it contains this text: {Binding Source={StaticResource LabelsManager}, Path=Labels.Text1}

    Is it possible to get the source in there?

    I simply need the variables to get the Resources.

    Another example:

    MessageBox.Show(“{Binding Source={StaticResource LabelsManager}, Path=Labels.Text1}”);

    I hope you know what I mean.

    Thanks in advance for your help ;)

    • April 15, 2012 5:45 pm

      For MessageBox, you don’t need to use a Binding expression:
      MessageBox.Show(Labels.Text1); At runtime the fwk will use the correct language resource file.

      The same for the Toggle Switch if it’s in code :

      toggleSwitch1.Content = Labels.Text1;

      • Deluxe permalink
        April 15, 2012 5:57 pm

        Hi Matthieu,

        thanks for the reply, but it isn’t working.

        The name “Labels” is not available in the actual context :/

      • April 15, 2012 6:07 pm

        Yes it’s not Labels, it’s the name of your Resource (resx file) and don’t forget to mark it as public if needed.

      • Deluxe permalink
        April 15, 2012 6:13 pm

        Hmmm sorry, I’m really new to this. Which file do you mean? I used the same file names like in your example. (Labels.resx, Labels.de.resx, LabelsManager.cs)

      • April 15, 2012 6:17 pm

        So it should be Labels.Text1 but youd need to change the Access Modifier option when you open the Labels.resx file (at the top) from “no code generation” to “Public” or “Internal”

      • Deluxe permalink
        April 15, 2012 6:17 pm

        Aaaaaaah, I got it!! I had to use the full path to the file ;)

        Thank you very much!

  7. Mathias permalink
    April 24, 2012 8:50 am

    Thank you!
    This worked perfect!

Trackbacks

  1. Дайджест технических материалов #5 (Windows Phone 7) - Oleksandr Krakovetskiy blog - Microsoft User Group Винница
  2. Localize the ApplicationBar « Windows Phone 7 Wonders

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

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: