How to implement .NET MAUI localization

Viewed 3477

I'm unable to find any direction on implementing localization for a MAUI app. I've read some info about localizing Xamarin apps but am unable to translate it forward to MAUI even after extensive web searching.

Can anyone point me to a reference that I may have missed?

3 Answers

Use Microsoft Extensions Localization package

Create Class For LocalizeExtension. Here AppStrings are ResourceFileName which you have given

[ContentProperty(nameof(Key))]
public class LocalizeExtension : IMarkupExtension
{
    IStringLocalizer<AppStrings> _localizer;

    public string Key { get; set; } = string.Empty;

    public LocalizeExtension()
    {
        _localizer = ServiceHelper.GetService<IStringLocalizer<AppStrings>>();
    }

    public object ProvideValue(IServiceProvider serviceProvider)
    {
        string localizedText = _localizer[Key];
        return localizedText;
    }

    object IMarkupExtension.ProvideValue(IServiceProvider serviceProvider) => ProvideValue(serviceProvider);
}

XAML

    <Button Text="{local:Localize Key}"/>

Check out this SampleApp for more details LocalizationDemo

Have a look at the .NET MAUI Reference Application for .NET 6 "Podcast App" you can find here: https://github.com/microsoft/dotnet-podcasts

It makes use of a resource file that contains localizable strings for the UI.

Maybe that helps you.

Try this - Create standard resources

  • "Add New Item/Resource File" > MauiApp1/Resources
  • set name "AppRes.resx"
  • create second lang "AppRes.ru.resx"
  • add strings

explorer resource view

how use in XAML

[...] xmlns:res="clr-namespace:MauiApp1.Resources" 

<Button Text="{x:Static res:AppRes.Title}" />

use code

//get lang as "en"
string lang = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

//toggle lang
if(lang == "ru")
{
    Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("ru-RU");
    Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("ru-RU");
}
else
{
    Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
    Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
}

//get translated title
//using MauiApp1.Resources;
string title = AppRes.Title

And for update just reset app

(App.Current as App).MainPage = new AppShell();

That's All

Related