I'm working on a Blazor project, where I am trying to add my first language to my application. I have gotten pretty far, where I can select a language from a multi-selection box and changes the language. My only problem is that it only changes the language in the current .razor file and not in the whole application.
I already set up the .resx files in my Resources
folder and added it like that:
serviceCollection.AddLocalization(options => options.ResourcesPath = "Resources");
This line of code is in a static function for the type IServiceCollection
:
public static IServiceCollection AddBlazorServices(this IServiceCollection serviceCollection)
{
serviceCollection.AddLocalization(options => options.ResourcesPath = "Resources");
return serviceCollection;
}
and this function is called finally in startup.cs:
public void ConfigureServices(IServiceCollection services)
{
var circuitRetentionPeriod = Configuration.GetValue("DisconnectedCircuitRetentionPeriodInMinutes", 3);
services.AddRazorPages();
services.AddServerSideBlazor()
.AddCircuitOptions(a => a.DisconnectedCircuitRetentionPeriod = System.TimeSpan.FromMinutes(circuitRetentionPeriod))
.AddHubOptions(hub => hub.MaximumReceiveMessageSize = 100 * 128 * 128); // 100 MB
services.AddScoped<CircuitHandler>((sp) => new CircuitHandlerService(sp.GetRequiredService<ILogger<CircuitHandlerService>>(), sp.GetRequiredService<CircuitsCounterService>()));
services.AddSingleton<CircuitsCounterService>();
services.AddScoped<CorrelationProvider>();
services.AddApplicationServices();
services.AddBlazorServices();
services.AddForeignServices();
}
I also already moved all strings in my application to the .resx files and added it back via the IStringLocalizer<>
. I translated also every .resx file into another language. Currently it displays the language based on your system-language in your device. Now I would like to control that via a razor-file.
In a razor file, I have a default <select> (default html-element) where I can select between languages. As soon as you click to one option, it fires the following method:
void RequestCultureChange()
{
if (string.IsNullOrWhiteSpace(selectedCulture))
return;
if (selectedCulture == "de-CH")
{
var culture = new CultureInfo("de-CH");
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}
else if (selectedCulture == "en-US")
{
var culture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}
}
As I said, this only changes the language in the current .razor file. Do you know what my potential mistake is?
I already did some research but did not find any solution. I also do not want any cookies with this information, since it's planned to save the data to the user profile in a database, in case some information has to be stored permanently to make it work.