Reputation: 109
So I'm attempting to add localization to the UWP application I'm working on. From what I've researched online I'm able to add it using the Mulitlingual App Toolkit. The one issue I run into is duplicate values in the resource file. For example imagine I need to label 2 different controls with the same value. The controls are a button (using the property button.Content) and a text block (using textBlock.Text). I'd like to only have one name/value pair in the resource file that can be used for both of these controls. Is there a way to do this? Also I'd like to be able to set these values in xaml. Thanks in advance.
Upvotes: 2
Views: 848
Reputation: 191
Localization for UWP in general
First, the default way of internationalization (i18n) and localization (l10n) is by using different .resw
(or .resx
for other environments like Xamarin) per language. In these files you store translated strings with some identifier key.
The Mulitlingual App Toolkit is a tool to facilitate and somewhat manage (e.g. tracking review status) the surrounding processes of actually translating the strings with people that possibly are not part of the actual dev team. But in the end, it too just generates the .resw
files like you could have done manually. So you don't HAVE to use the MAT in order to localize your App.
Implementing it
The way to achieve what you want would be to use some sort of Binding.
I personally like to use a custom markup extension to be able to distinguish between actual dynamic data and hardcoded internationalized strings. Furthermore it keeps the Binding short. This would then look something like Title="{i18n:Translate GlossaryPageTitle}"
.
Unfortunately, Markup Extensions don't seem to be available in UWP as of yet (source).
So the way to go (simpler anyway) is to use a Converter and pass the Key for the desired Text as a parameter.
Like this:
Title="{x:Bind Converter={StaticResource LocalizationConverter}, ConverterParameter=GlossaryPageTitle}"
.
Where the implementation of the converter would look like this:
public class LocalizationConverter : IValueConverter
{
private readonly ResourceLoader _resourceLoader = ResourceLoader.GetForViewIndependentUse("/Resources");
public object Convert(object value, Type targetType, object parameter, string language)
{
if (parameter is string resourceId)
{
return _resourceLoader.GetString(resourceId);
}
return DependencyProperty.UnsetValue;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotSupportedException();
}
}
Then register the Converter somewhere in your App (either per view or globally) and you're good to go.
Upvotes: 4