Localization Generator
Do you use Microsoft.Extensions.Localization
? It provides a great set of abstractions, but it removes the IDE tooling that provided strong typing of the available keys. This library
looks to solve that by generating a class around a IStringLocalizer
class.
Given this directory structure:
- MyViewModel.cs
- MyViewModel.resx
- MyViewModel.fr-ca.rex
- Folder1\FolderViewModel.cs
- Folder1\FolderViewModel.resx
- Folder1\FolderViewModel.fr-ca.resx
We will generate these:
- MyViewModelLocalized.g.cs (RootNamespace.MyViewModelLocalized)
- Folder1.FolderViewModelLocalized.g.cs (RootNamespace.Folder1.FolderViewModelLocalized)
- ServiceCollections.g.cs
- Install
- Install
- In your MauiProgram.cs, do the following
builder.Services.AddStronglyTypedLocalizations(); // this will also add the AddLocalization() call
- Now add an
.resx
file to your project that matches the name of class (ie. ViewModel, Controller, Service, etc). - Now inject the strongly typed classes
public class MyViewModel{public MyViewModel(MyViewModelLocalized localizer) // same namespace and class name with "Localized" suffix=> this.Localizer = localizer;public MyViewModelLocalized Localizer { get; }}
- Now bind (xaml intellisense will pick it up)
<Label Text="{Binding Localizer.MyKey}" />
If the “class” beside the resource does not exist, a compile error will occur with the generated code
Generate Classes with Internal Accessor
Section titled “Generate Classes with Internal Accessor”<PropertyGroup> <GenerateLocalizersInternal>True</GenerateLocalizersInternal></PropertyGroup>