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();
}
Full code is on Github (Blazor 8.0 server side) :
Click here to check the code