Blazor 8.0服务器端切换语言后Index页面本地化文本未更新
Blazor 8.0 服务器端本地化切换不更新问题修复
核心问题原因
Blazor服务器端组件不会自动随文化变更触发重新渲染,需手动实现状态通知与组件刷新逻辑。
具体修复步骤
完善CultureState的通知机制
确保CultureState类继承INotifyPropertyChanged接口,在文化变更时触发事件:public class CultureState : INotifyPropertyChanged { private CultureInfo _currentCulture; public CultureInfo CurrentCulture { get => _currentCulture; set { if (_currentCulture != value) { _currentCulture = value; OnPropertyChanged(nameof(CurrentCulture)); } } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }在Index组件中监听文化变更并刷新
注入CultureState,监听其变更事件并调用StateHasChanged()刷新组件:@inject CultureState CultureState @implements IDisposable <p>@Localizer["WelcomeMessage"]</p> @code { [Inject] public IStringLocalizer<Index> Localizer { get; set; } protected override void OnInitialized() { CultureState.PropertyChanged += OnCultureChanged; } private void OnCultureChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(CultureState.CurrentCulture)) { StateHasChanged(); } } public void Dispose() { CultureState.PropertyChanged -= OnCultureChanged; } }修正语言切换组件的状态更新逻辑
切换语言时,同步更新CultureState与当前线程文化:private void SetCulture(string cultureCode) { var culture = new CultureInfo(cultureCode); CultureState.CurrentCulture = culture; CultureInfo.CurrentCulture = culture; CultureInfo.CurrentUICulture = culture; }验证Program.cs服务配置
确保CultureState注册为单例,本地化服务配置完整:builder.Services.AddSingleton<CultureState>(); builder.Services.AddLocalization(options => options.ResourcesPath = "Resources"); builder.Services.AddRazorComponents() .AddInteractiveServerComponents() .AddLocalization(); }
内容的提问来源于stack exchange,提问作者Kasrak
相关产品推荐
相关产品推荐

