SurenSaluka
SurenSaluka

Reputation: 1591

Localize strings in XAML UI in UWP

I have a resource entry named info_278 in the Resources.resw file on my UWP app. I have 3 scenarios where I need to use this resource but looks like I need to duplicate this to cater to different scenarios. Scenarios are as follows.

  1. Error message content from code

    var displayErrorOnPopup = ResourceHandler.Get("info_278");

  2. TextBlock Text property from XAML (Looks like a new entry needed as info_278.Text)

    <TextBlock x:Uid="info_278" Margin="10,0,0,0" />

  3. Button Content property from XAML (Looks like a new entry needed as info_278.Content)

    <Button x:Uid="info_278" Margin="10,0,0,0" />

How do I proceed without duplicating this resource in the .resw file?


enter image description here

Upvotes: 2

Views: 969

Answers (2)

francescot
francescot

Reputation: 61

You could create a markup extension. I've used this in WinUI 3, but should work in UWP too.

using Microsoft.UI.Xaml.Markup;
using Windows.ApplicationModel.Resources;

namespace MyApp;

[MarkupExtensionReturnType(ReturnType = typeof(string))]
public class StringResourceExtension : MarkupExtension
{
    private static readonly ResourceLoader _resourceLoader = new();

    public StringResourceExtension() { }

    public string Key { get; set; } = "";

    protected override object ProvideValue()
    {
        return _resourceLoader.GetString(Key);
    }
}

Then in the XAML:

...
local="using:MyApp"
...

<TextBlock Text="{local:StringResource Key=info_278}" />
<Button Content="{local:StringResource Key=info_278}" />

Upvotes: 3

Roy Li - MSFT
Roy Li - MSFT

Reputation: 8666

The only way to avoid duplication is to set the string value in code-behind using ResourceLoader. Because you could direct access to the specific property of the target control. Like this:

var resourceLoader = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView();
this.TextBlock.Text = resourceLoader.GetString("info_278");

If you are not going to do it in the code behind, then I have to say there is no way to avoid the duplication of the resource string. You should add info_278.Text and info_278.Content for different XAML scenarios.

Upvotes: 3

Related Questions