I am working on an app with a lot of different languages. This is really great because there is a lot more chances that the user get the app in its spoken tongue. You can read more on this topic on MSDN.
Then I wanted to get a basic information : the language used by the app. Let’s say that the user is spanish and that I didn’t translate my app for this tongue then the app could be in english because it’s the one tongue matching the best its preference. The “english” won’t necessary be the first language declared in my manifest but the best one for the user.
By using a ResourceLoader object, you can get any string in the right language but I didn’t find an easy way to get the actually used language.
By digging into the WinRT APIs, I found a way to get this information and it could help you.
The trick is to use the MainResourceMap of the app to retrieve a resource candidate for a resource key I know being in all my resources files. With this ResourceCandidate, I can get the ResourceQualifier which made the framework choose this resource. On this qualifier, I can then retrieve the name of the used language…
//I have a resource file named "Resources" for each my language
// and each one has a ‘AResource’ object in it.
var namedResource = ResourceManager.Current.MainResourceMap
.FirstOrDefault(nR => nR.Key == "Resources/AResource").Value;
//I resolve this resource
var resourceCandidate = namedResource.Resolve();
//The qualifier let me know the used language code.
var resourceQualifier= resourceCandidate.Qualifiers.FirstOrDefault();
var languageCode = resourceQualifier.QualifierValue;
You can also get interesting information from the resourceCandidate object :
- IsMatch: is this resource found using the a language defined in your manifest.
- IsDefault : is this resource found using the default “language” (the one defined in your manifest) ?
- Score : the score of the retrieved resourceCandidate in the resource-matching algorithm used by the framework
An interesting thing is that you can also know the score of the retrieved resourceCandidate in the resource-matching algorithm used by the framework. It’s the Score property of the ResourceCandidate.
An another solution is to put the language code of each resource file inside the resource. Then you could use the ResourceLoader to get it.
Things I tried
I also tried to use the ApplicationLanguages.ManifestLanguages list but with this API I can get the language declared in my manifest, not the one actually used by the app.
Same thing with ApplicationLanguages.Languages which let me know the user defined languages but not the one actually used by the app.
Do you know a better way ?