0

I have a Blazor WASM app running on .NET Core 3.1 with localization configured as per this MS doc. Everything is working great until here, the app is localized and I'm able to switch between languages.

Now, I am trying to render a component with Resource content displayed using a given culture. Here's my attempt using a parent component passing in a given culture name to a child component that should display the localized Resources strings.

@using System.Globalization

@foreach(var lang in supportedCultures)
{
    <LocalizedComponent CultureName="@lang" ResourceName="French" />
}

@code {
    private string[] supportedCultures = new[] { "en", "fr", "en-US", "fr-FR", "fr-CA" };
}

LocalizedComponent.razor

@using System.Globalization
@using System.Threading;

<h3>Content for @GivenCulture.ToString()</h3>
<p>Value from Resource property: @Resource.French</p>
<p>Value from Resource Manager (using GetString method): @Resource.ResourceManager.GetString(ResourceName, GivenCulture)</p>
<p>Value from Localizer: @Localizer[ResourceName]</p>

@code {

    [Parameter]
    public string ResourceName { get; set; }

    [Parameter]
    public string CultureName { get; set; }

    private CultureInfo GivenCulture => new CultureInfo(CultureName);

    [Inject]
    private IStringLocalizer<Resource> Localizer { get; set; }

    protected override async Task OnInitializedAsync()  
    {
        CultureInfo.DefaultThreadCurrentCulture = GivenCulture;
        CultureInfo.DefaultThreadCurrentUICulture = GivenCulture;

        //same result using:
        //Thread.CurrentThread.CurrentUICulture = GivenCulture;

        var temp = Resources.Resource.ResourceManager.GetObject(ResourceName, GivenCulture).ToString();

        await base.OnInitializedAsync();
    }

}

I have the corresponding Resource files created as Resource.resx and Resource.fr.resx, with a localized string for a Resource "French". The app content is localized just fine when I switch between the languages in the UI, however, the localized component does not display the given culture resources ad-hoc.

Is there a way to force an individual component to display localized content for a given culture in Blazor?

Results:

enter image description here

Canica
  • 2,650
  • 3
  • 18
  • 34

0 Answers0