Search code examples
blazorlocalizationblazor-server-sidecultureinfo

Change Index page UI item (localization) by Clicking a button in the Layout's component


Here we have a very simple application with 3 major parts: Index file with 1 localized text, A component with just a button that switches between 2 languages, and 3rd the MainLayout, which is used by the Index page and contains the LangBar component.

Let me share all the needed code:

We used localization only in a single text in the Index.razor:

 <h3>@Loc["stWelcome"]</h3>

Index.Razor (or Home.razor)

@page "/"
@inject IStringLocalizer<Index> Loc
@inject CultureState CultureState

<h3>@Loc["stWelcome"]</h3>

@code {
    protected override void OnInitialized()
    {
        CultureState.OnCultureChanged += HandleCultureChanged;
    }

    private void HandleCultureChanged()
    {
        StateHasChanged();
    }

    void Dispose()
    {
        CultureState.OnCultureChanged -= HandleCultureChanged;
    }
}

LangBar Usage (Our main component) : MainLayout.razor :

            <LangBar OnLanguageChanged="@HandleLanguageChange" />

MainLayout.razor Code:

@code 
{
     private void HandleLanguageChange()
     {
         //NavigationManager.NavigateTo(NavigationManager.Uri, true);
         StateHasChanged();
     }

     protected override void OnInitialized()
     {
         // Ensure initial UI update based on stored culture
         StateHasChanged();
     }    
}

CultureState class

    public string CurrentCulture { get; set; }

    public event Action OnCultureChanged;

    public void SetCulture(string culture)
    {
        CurrentCulture = culture;
        OnCultureChanged?.Invoke();
    }

In Program.cs I added the needed services and also registered our own CultureState for global notifications, Resx files are also created and are working properly.

The problem is that after changing the language Index page doesn't update the localized string.

Full code is on Github (Blazor 8.0 server side) :

Click here to check the code


Solution

  • Looking at your github code you seem to be using per page/component interactivity location. This means you would need to add @rendermode InteractiveServer to your index page to see any changes.

    Since the MainLayout is also rendered statically you cannot pass the EventCallback OnLanguageChanged from there and a StateHasChanged in the MainLayout will also have no effect.

    If you want to have your LangBar in the MainLayout you could achieve this by using a shared service (e.g. a scoped service) that populates the event and each page subscribing to that event calling StateHasChanged