Vitor Mikaelson
Vitor Mikaelson

Reputation: 53

UWP C# Localization

So I'm pretty new to development world and I already know how to localize on XAML [just put a x:Uid, pretty easy]. But how can I do that on code? I already tried a few things, but with no success. Can someone help me? Here is the code I'm trying to assign:

 private void OnShowLoadingChanged(Visibility newVisibility)
    {
        ui_progressRing.IsActive = newVisibility == Visibility.Visible;
        ui_progressRing.Visibility = Visibility.Visible;
        ui_textBlock.Text = "Loading Comments";
        PlayAnimation(newVisibility);
    }

Obviously is the Loading Comments string, and I know that I have to use GetString, but I'm just not doing right...

Upvotes: 1

Views: 807

Answers (2)

Ann Yu
Ann Yu

Reputation: 137

In the resource file, [tbImage.Text], [imgMain.Source] have been setted. You can use x:Uid in xaml. And in c# methods, to get resource according to the language, you can use this code snippet:

ResourceContext resourceContext = new ResourceContext(); 
resourceContext.Languages = new string[] { language }; 
ResourceMap resourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources"); 
string imageSource= resourceMap.GetValue("imgMain/Source", resourceContext).ValueAsString;  
this.imgMain.Source = new BitmapImage(new Uri(imageSource, UriKind.RelativeOrAbsolute)); 
this.tbImage.Text = resourceMap.GetValue("tbImage/Text", resourceContext).ValueAsString; 

There's a sample about UWP localization in MSDN. https://code.msdn.microsoft.com/how-to-create-a-localizatio-c61f4b37

Upvotes: 0

Paul Abbott
Paul Abbott

Reputation: 7211

You need a resource loader, but you can get one and reuse it like this:

private ResourceLoader MyResourceLoader
{
    get
    {
        if (_resourceLoader == null)
            _resourceLoader = new ResourceLoader();
         return _resourceLoader;
    }
}
private ResourceLoader _resourceLoader { get; set; }

Then it's just

MyResourceLoader.GetString(key)

Upvotes: 2

Related Questions