I followed the sample project in https://github.com/pranavkm/LocSample
Here is the code of Program.cs:
using System; using System.Net.Http; using System.Collections.Generic; using System.Threading.Tasks; using System.Text; using Microsoft.AspNetCore.Components.WebAssembly.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Blazored.LocalStorage; using System.Globalization; using System.Diagnostics; using Microsoft.Extensions.Options; namespace Temple { public class Program { public static async Task Main(string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.RootComponents.Add<App>("app"); builder.Services.AddTransient(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); builder.Services.AddLocalization(options => options.ResourcesPath = "Resources"); builder.Services.AddBlazoredLocalStorage(); var host = builder.Build(); var localStorage = host.Services.GetRequiredService<ILocalStorageService>(); string CurrentLanguage=await localStorage.GetItemAsync<string>("Language"); Debug.WriteLine(CurrentLanguage); if (!string.IsNullOrEmpty(CurrentLanguage)) { var culture = new CultureInfo(CurrentLanguage); CultureInfo.DefaultThreadCurrentCulture = culture; CultureInfo.DefaultThreadCurrentUICulture = culture; } await host.RunAsync(); } } }
And here is the code of index.razor:
@page "/" @inject IStringLocalizer<Index> Localizer; @inject NavigationManager Nav @inject Blazored.LocalStorage.ILocalStorageService localStorage<h1>@Localizer["Test"]</h1><button @onclick="ABC">123123</button> Welcome to your new app. @code{ public void ABC() { localStorage.SetItemAsync("Language", "zh-Hans"); Nav.NavigateTo(Nav.Uri, forceLoad: true); } }
And here is the file list:
https://i.stack.imgur.com/H8wAS.png
As you see, I have using the Blazored.LocalStorage nuget package to achieve the local storage and it works well.
The problem is when I clicked the button in index.razor. The language never changes to Chinese.
What's more, I found a strange problem. After I modified the code of void ABC in index.razor like this:
@code{
public void ABC()
{
localStorage.SetItemAsync("Language", "en");
Nav.NavigateTo(Nav.Uri, forceLoad: true);
}
}
When I clicked the button, it changed the language to English correctly.
What's wrong with this?