How do you localize MudBlazor DataGrid in Blazor WebAssembly?

I'm working on a Blazor (.NET 7) webassembly app using MudBlazor components and was wondering how and if it's possible to localize f.ex the DataGrid for "is-IS"? I have already done the basic localization using .resx files.

I created a WebAssemblyHostExtension and reference it in Program.cs and that works just fine using IStringLocalizer but MudBlazor components are just in english. What am I missing?

builder.Services.AddBlazoredLocalStorage();

var host = builder.Build();
await host.SetDefaultCulture(); // Retrieves local storage value and sets the thread's current culture.
await host.RunAsync();

 public async static Task SetDefaultCulture(this WebAssemblyHost host)
    {
      

        CultureInfo cultureInfo;

        try
        {
            var localStorage = host.Services.GetRequiredService<ILocalStorageService>();
            var cultureString = await localStorage.GetItemAsync<string>("culture");

            if (!string.IsNullOrWhiteSpace(cultureString))
            {
                cultureInfo = new CultureInfo(cultureString);
            }
            else
            {
                cultureInfo = new CultureInfo(LocalizerSettings.NeutralCulture.Name);
            }
        }
        catch(Exception ex
        {
            cultureInfo = new CultureInfo(LocalizerSettings.NeutralCulture.Name);
        }

        CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
        CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
    }

Upvotes: 3

Views: 1570

Answers (1)

willingdev
willingdev

Reputation: 9646

in blazor wasm hosted client project:

  1. Add these lines to program.cs :

    CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.CreateSpecificCulture("fr-FR"); builder.Services.AddTransient<MudLocalizer, DictionaryMudLocalizer>();

  2. Add BlazorWebAssemblyLoadAllGlobalizationData with true value to the .csproj file of client project in PropertyGroup section: BlazorWebAssemblyLoadAllGlobalizationData>true</BlazorWebAssemblyLoadAllGlobalizationData

  3. create a DictionaryMudLocalizer class :

    public class DictionaryMudLocalizer : MudLocalizer { private readonly Dictionary<string, string> _localization;

     public DictionaryMudLocalizer()
     {
         _localization = new()
         {
             { "MudDataGrid.Unsort", "حذف سورت" },
         };
     }
    
     public override LocalizedString this[string key]
     {
         get
         {
             _localization.TryGetValue(key, out var res);
             return new(key, res);
         }
     }
    

    }

to make it use the custom localizer, the CurrentUICulture can't be any of the english cultures

https://mudblazor.com/features/localization#dictionary-based-example

Upvotes: 1

Related Questions