C# change app language programmatically UWP realtime
We can use ApplicationLanguages.PrimaryLanguageOverride to change the language during runtime without restart the app.
For example: I have two languages supported "en" and "fr", localized message will show up in textblock.
Add using Windows.Globalization;
Change the default language from "en" to "fr" by
ApplicationLanguages.PrimaryLanguageOverride = "fr";
Re-navigate to the current page to refresh the UI.
Frame.Navigate(this.GetType());
Note that, you need to compare the PrimaryLanguageOverride with the system culture to set the language for next app launch, because the PrimaryLanguageOverride setting is persisted. And if you have page cache enabled, when you apply a different language on the fly, you need to clear the cache by setting Frame.CacheSize = 0;
first then set it back.
Some addition to Alan Yao's answer. There's one missing piece:
After you set the Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride
and before re-navigating to the current page, you must call these two functions:
Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView().Reset();
Windows.ApplicationModel.Resources.Core.ResourceContext.GetForViewIndependentUse().Reset();
This way you won't need the Task.Delay()
workaround mentioned by Michael Woolsey.
One more important last step: when creating a Store package, you should make sure to set the "Generate app bundle" setting value to "Never". Reason from this article:
Because otherwise, it will create a bundle. It means that he will cut your application into different parts to optimize the download. Only the parts that are relevant for the devices will be downloaded. For example, if there are the assets in different resolution, it will only download the ones that are suitable for the device. Same thing for languages, it will only download the resources file relevant to the language of the device. So if you try to change language, it will fall still fall back on the same base language, because others are not installed.
@ThisWillDoIt and @Herdo
I added a delay so that the "First" time it would work in my situation:
Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride = languageCode;
await Task.Delay(100);
Frame.Navigate(this.GetType());
Hope it helps work for you.