Explanation
MudBlazor itself provides English language strings for texts found in e.g. the MudDataGrid
filter options.
By registering a custom MudLocalizer
implementation as a Service, you can provide custom translations.
Register Service
Add the following in Program.cs
to register your custom localization service.
AddTransient
can be replaced with TryAddTransient
and the scope can be changed to Scoped
or Singleton
depending on your exact implementation.
using Microsoft.Extensions.DependencyInjection; using MudBlazor; builder.Services.AddTransient<MudLocalizer, CustomMudLocalizerImpl>();
ResX Example
An example MudLocalizer
implementation using Microsoft default IStringLocalizer
.
Using ResX, you'll have to leave the default culture translations file empty if you want to use English as the fallback language for missing translations. Otherwise, the default culture values will be used as a fallback for all non-English languages.
using Microsoft.Extensions.Localization; using MudBlazor; internal class ResXMudLocalizer : MudLocalizer { private IStringLocalizer _localization; public ResXMudLocalizer(IStringLocalizer<ResXLanguageResource> localizer) { _localization = localizer; } public override LocalizedString this[string key] => _localization[key]; }
Dictionary based Example
An example implementing MudLocalizer
using a hardcoded dictionary for the translations.
Note that LocalizedString.ResourceNotFound
should be true, if there is no custom translation for a given key.
If LocalizedString.ResourceNotFound
is true, the included English localization will be used.
using System; using System.Collections.Generic; using System.Threading; using Microsoft.Extensions.Localization; using MudBlazor; internal class DictionaryMudLocalizer : MudLocalizer { private Dictionary<string, string> _localization; public DictionaryMudLocalizer() { _localization = new() { { "MudDataGrid.is empty", "ist leer" }, { "MudDataGrid.is not empty", "ist nicht leer" }, { "MudDataGrid.contains", "enthält" }, { "MudDataGrid.not contains", "enthält nicht" }, }; } public override LocalizedString this[string key] { get { var currentCulture = Thread.CurrentThread.CurrentUICulture.Parent.TwoLetterISOLanguageName; if (currentCulture.Equals("de", StringComparison.InvariantCultureIgnoreCase) && _localization.TryGetValue(key, out var res)) { return new(key, res); } else { return new(key, key, true); } } } }