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.
Don’t forget to choose “public” as the class visibility level (for the binding).
Unload your project and edit the csproj file to add your supported language:
(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:
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.
Add an instance of the class as a resource in the application (App.xaml):
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):
If you change the language of the emulator and restart it,you will see that the label gets the correct value :
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 famousINotifyPropertyChanged interface. So here’s the code of the new class:
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:
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.
I used this post from Tim Heuer for the dynamic version.
Here’s the source code of the project on GitHub.