英文:
Change resource dictionary in a blazor component
问题
I created pages in Blazor where I manage the language change with Localization. Each page has a unique source dictionary. I inject the dictionaries with this code: @inject IStringLocalizer<Login> Localizer
.
Since part of the design is the same, I would like to create a component, but no matter what I have tried, I cannot make it.
How can it be solved that the value can always be changed dynamically? Does anyone have an idea how to solve this?
Razor page:
<MyComponent ResourceName="Login"></MyComponent>
@code {
[Parameter]
public string ResourceName { get; set; }
}
This is my code in the component:
[Inject]
public IStringLocalizerFactory LocalizerFactory { get; set; }
private IStringLocalizer Localizer { get; set; }
protected override void OnInitialized()
{
Localizer = LocalizerFactory.Create<ResourceDictionary>(ResourceName);
}
The error message is most of the time: "The non-generic method 'IStringLocalizerFactory.Create(Type) cannot be used with type arguments," or after some changes "cannot convert from System.Type to string."
英文:
I created pages in Blazor where I manage the language change with Localization. Each page has a unique source dictionary. I inject the dictionaries with this code : @inject IStringLocalizer<Login> Localizer.
Since part of the design is the same, I would like to create a component, but no matter what I have tried, I cannot make it.
How can it be solved that the value can always be changed dynamically? Does anyone have an idea how to solve this?
Razor page:
<MyComponent ResourceName="Login"></MyComponent>
@code {
[Parameter]
public string ResourceName {get; set; }
}
This is my code in the component:
[Inject]
public IStringLocalizerFactory LocalizerFactory { get; set; }
private IStringLocalizer Localizer { get; set; }
protected override void OnInitialized()
{
Localizer = LocalizerFactory.Create<ResourceDictionary>(ResourceName);
}
The error message is most of the time: "The non-generic method 'IStringLocalizerFactory.Create(Type) cannot be used with type arguments", or after some changes "cannot convert from System.Type to string
答案1
得分: 0
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
现在您可以在您的 Component.razor.cs 中使用 [Inject] private IStringLocalizer<Component> L { get; set; } = default!;
。
英文:
How does your program.cs look like?
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
With this option all my resources are in the folder Resources
this folder has the same sub structure as the root directory.
- Pages
-- Component.razor - Resources
-- Pages
--- Component.en-US.resx
Now you can use [Inject] private IStringLocalizer<Component> L { get; set; } = default!;
in your Component.razor.cs
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论