Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Localization on the fly in WinRT app

In WinRT app newer localization is applied when app is restarted (using code or by changing language from control panel). What to do if I want to change the localized strings on-the-fly, without restarting the app?

Suppose I have combo box with different languages. If user selects any language, all the strings would be translated using resource.

I came across this code, but it works only if I put it in App constructor, that's also on launch only. I can't make it a static method as it doesn't work.

var culture = new System.Globalization.CultureInfo("en-US");
Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride = culture.Name;
System.Globalization.CultureInfo.DefaultThreadCurrentCulture = culture;
System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = culture;

I want something like below given image. Image is from CodeProject article.

enter image description here

like image 225
Farhan Ghumra Avatar asked Jan 02 '14 13:01

Farhan Ghumra


1 Answers

You need to reset the context of the resource manager.

For Windows 8.1:

var resourceContext = Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView();
resourceContext.Reset();

You will still need to force your page to redraw itself and thus re-request the resources to get the changes to take place. For Windows 8, you can see https://timheuer.com/blog/archive/2013/03/26/howto-refresh-languages-winrt-xaml-windows-store.aspx

Note that PrimaryLanguageOverride is persisted and from your problem description it looks like you would be correctly setting it in response to a user initiated action. I don't think that you have to override the thread cultureinfos except as soon as the user initiates a change as well.

Note also that PrimaryLanguageOverride takes a BCP 47 language tag whereas the CultureInfo uses a locale name which have subtle distinctions.

like image 116
Eric MSFT Avatar answered Sep 23 '22 03:09

Eric MSFT