DotNet MAUI: Language Translation Markup Extension

Your app should be offered in many languages. Even just presenting the buttons for the user in the language of the phone will help. You can use Google to translate these simple texts. It’ll get “Save” and “Cancel” and “Login” correct. Making this effort will go a long way to impressing users, even if the app isn’t 100% translated. In this article I’ll show you how to set the text of your buttons to languages defined in your RESX files.

I’ll assume you’ve set up your MAUI for localization.

Let’s add a few RESX files. Note that currently you must name the files as the language 2 letter code only. Word.fr.resx is fine, Words.fr-ca.resx is not. Hopefully that’ll get fixed.

Set each file you make to use the Custom Tool PublicResXFileCodeGenerator

Next, add this MarkupExtension class:

 [ContentProperty("Text")]
public class TranslateExtension : IMarkupExtension
{
    readonly CultureInfo ci = null;
    const string ResourceId = "YourApp.Resx.Words";

    static readonly Lazy<ResourceManager> ResMgr = new Lazy<ResourceManager>(
        () => new ResourceManager(ResourceId, IntrospectionExtensions.GetTypeInfo(typeof(TranslateExtension)).Assembly));

    public string Text { get; set; }

    public TranslateExtension()
    {
        ci = System.Globalization.CultureInfo.CurrentCulture; 
    }

    public object ProvideValue(IServiceProvider serviceProvider)
    {
        if (Text == null)
            return string.Empty;

        var translation = ResMgr.Value.GetString(Text, ci);
        if (translation == null)
        {
#if DEBUG
            throw new ArgumentException($"Key '{Text}' was not found in resources '{ResourceId}' for culture '{ci.Name}'.");
#else
                translation = Text; // HACK: returns the key, which GETS DISPLAYED TO THE USER
#endif
        }
        return translation;
    }
}

Open your XAML page

In the header add the namespace where the above file was added:

xmlns:helpers="using:YourApp.Helpers"

Now, add this to your XMAL ( any with Text as a property)

<Button Text="{helpers:Translate Close}"   />

Done! Your button will be an the language of the phone magically.

Leave a comment