Install
| Product | Versions |
|---|---|
| .NET |
README
Irihi.Lingua
A C# source generator that turns .resx or .json resource files into a strongly-typed, reactive Avalonia i18n manager.
Each resource key becomes an IObservable<string?> property that pushes a new value whenever the active culture changes โ no manual INotifyPropertyChanged wiring required.
Special Thanks
Special thanks to sylinko/everywhere โ this project was inspired by it.
Highlights
- NativeAOT-compatible (native smoke checks).
- Designed and optimized for Avalonia.
- Usable from both XAML and ViewModel code.
- Decentralized i18n managers: define separate resource managers in different classes and choose the granularity that fits your app โ per feature, module, screen, or any other boundary you prefer.
- Supports both
.resx(XML) and.jsonresource formats.
Installation
Add the NuGet package to your project:
<PackageReference Include="Irihi.Lingua" />
The package bundles both the runtime library and the Roslyn source generator. No separate analyzer reference is needed.
Quick Start
1. Create your .resx files
Create a base resource file and one file per culture you want to support.
The culture variant files must follow the <BaseName>.<culture>.resx naming convention.
Resources/Strings.resx (default / invariant culture):
<?xml version="1.0" encoding="utf-8"?>
<root>
<data name="App_Title" xml:space="preserve">
<value>My Application</value>
</data>
<data name="Greeting_Message" xml:space="preserve">
<value>Hello!</value>
</data>
</root>
Resources/Strings.zh-Hans.resx (Simplified Chinese):
<?xml version="1.0" encoding="utf-8"?>
<root>
<data name="App_Title" xml:space="preserve">
<value>ๆ็ๅบ็จ็จๅบ</value>
</data>
<data name="Greeting_Message" xml:space="preserve">
<value>ไฝ ๅฅฝ๏ผ</value>
</data>
</root>
2. Add the resource files as AdditionalFiles
The generator reads all .resx files listed as AdditionalFiles in your project file.
You can include them individually or use a wildcard to add every resource file in a folder.
<ItemGroup>
<AdditionalFiles Include="Resources\Strings.resx" />
<AdditionalFiles Include="Resources\Strings.zh-Hans.resx" />
<!-- Or include all .resx files under Resources -->
<AdditionalFiles Include="Resources\**\*.resx" />
</ItemGroup>
3. Declare the language manager
Apply [LinguaManager] to a partial class, pointing it at the base .resx file.
The source generator fills in the rest at build time.
The class name is entirely up to you, and you can define as many [LinguaManager] classes in one application as you need โ each one is controlled by you.
[LinguaManager("./Resources/Strings.resx")]
public partial class LanguageManager;
4. Subscribe to observable strings
Each resource key is exposed as an IObservable<string?> property on the singleton Instance.
Subscribers receive the current value immediately (behaviour-subject semantics) and then every subsequent update.
using System.Globalization;
// Subscribe โ current value is emitted immediately on Subscribe
using var titleSub = LanguageManager.Instance.App_Title.Subscribe(
title => Console.WriteLine($"Title: {title}"));
using var greetingSub = LanguageManager.Instance.Greeting_Message.Subscribe(
msg => Console.WriteLine($"Greeting: {msg}"));
5. Switch the active culture
Call UpdateCulture at any time to push new values to all active subscribers.
The method walks the culture hierarchy (e.g. zh-Hans-CN โ zh-Hans โ invariant) until a matching resource file is found.
// Switch to Simplified Chinese
LanguageManager.Instance.UpdateCulture(new CultureInfo("zh-Hans"));
// Revert to the default (invariant) culture
LanguageManager.Instance.UpdateCulture(CultureInfo.InvariantCulture);
JSON Source Format
In addition to .resx, .json files are also supported.
Just point [LinguaManager] at a .json file โ the file extension tells the generator which format to use.
Nested object flattening
Nested JSON objects are flattened into underscore-separated property names.
Only leaf values of type string become resource keys โ numbers, booleans, and null are ignored.
Resources/Strings.json:
{
"a": "Content A",
"b": "Content B",
"c": {
"x": "Content X",
"y": "Content Y",
"z": {
"m": "Content M",
"n": "Content N"
}
}
}
Generated properties: a, b, c_x, c_y, c_z_m, c_z_n
Culture variants
Culture-specific JSON files follow the same <BaseName>.<culture>.json convention as .resx:
Resources/Strings.json โ default / invariant
Resources/Strings.zh-Hans.json โ Simplified Chinese
Registration
Add JSON files as AdditionalFiles alongside your .resx files:
<ItemGroup>
<AdditionalFiles Include="Resources\Strings.json" />
<AdditionalFiles Include="Resources\Strings.zh-Hans.json" />
<!-- Or include all .json files -->
<AdditionalFiles Include="Resources\**\*.json" />
</ItemGroup>
Manager declaration
Use a separate manager class for JSON resources (or replace your .resx manager entirely):
[LinguaManager("./Resources/Strings.json")]
public partial class JsonLanguageManager;
Usage
The generated API is identical โ Instance, UpdateCulture, Keys, and observable properties work the same way:
// { "app": { "title": "Hello" } } โ app_title
using var sub = JsonLanguageManager.Instance.app_title.Subscribe(
t => Console.WriteLine(t));
JsonLanguageManager.Instance.UpdateCulture(new CultureInfo("zh-Hans"));
Mixing RESX and JSON
You can define as many [LinguaManager] classes as you need โ one project can use both .resx and .json managers side by side, each with its own resource files. The generators run independently and produce completely separate output types.
Avalonia Usage
ViewModel + stream binding (^)
Expose the observable string properties from your view-model and bind them in XAML using the ^ stream-binding operator.
public class MainWindowViewModel
{
public IObservable<string?> AppTitle => LanguageManager.Instance.App_Title;
public IObservable<string?> GreetingMessage => LanguageManager.Instance.Greeting_Message;
}
<TextBlock Text="{Binding AppTitle^}" />
<TextBlock Text="{Binding GreetingMessage^}" />
TranslateExtension markup extension
For direct XAML bindings without a view-model wrapper, use the Translate markup extension together with the generated Keys nested class.
TranslateExtension is registered under the standard Avalonia XML namespace (https://github.com/avaloniaui) via XmlnsDefinition, so no additional namespace declaration is required.
Add only a local: alias for the namespace that contains your LanguageManager:
<Window xmlns="https://github.com/avaloniaui"
xmlns:local="using:YourAppNamespace">
</Window>
Then use the extension:
<TextBlock Text="{Translate {x:Static local:LanguageManager+Keys.App_Title}}" />
<TextBlock Text="{Translate {x:Static local:LanguageManager+Keys.Greeting_Message}}" />
The extension resolves the LinguaKey from the Keys class, looks up the corresponding IObservable<string?> and converts it into an Avalonia binding that updates automatically when the culture changes.
FormatTranslateExtension markup extension
Use FormatTranslateExtension (or FormatTranslate in XAML) when the resource is a format string (for example, "Page {0} {1}") and you need to combine localized text with dynamic values.
FormatKey points to the format template, and nested TranslateEntry elements provide arguments in order:
TranslateEntry Key="..."uses another localized key as an argument.TranslateEntry Binding="..."uses a normal Avalonia binding as an argument.
<TextBlock>
<TextBlock.Text>
<FormatTranslate FormatKey="{x:Static local:LanguageManager+Keys.Page_Template}">
<TranslateEntry Binding="{Binding #page.Value}" />
<TranslateEntry Key="{x:Static local:LanguageManager+Keys.Greeting_Message}" />
</FormatTranslate>
</TextBlock.Text>
</TextBlock>
In this example, {0} is filled by #page.Value and {1} is filled by Greeting_Message.
When either the current culture changes or any bound argument value changes, the final text is recomputed automatically.
Formatting uses the owning manager's active culture (passed to the converter through an internal trailing binding), so number and date arguments follow the selected language rather than the thread culture.
Format from C# code
FormatTranslate's counterpart for ViewModel code is the fluent Format builder. It starts from a format-template key and chains arguments with Arg:
public class MainWindowViewModel : INotifyPropertyChanged
{
// Page and TotalPages raise PropertyChanged ...
public IObservable<string?> PageText =>
LanguageManager.Keys.Page_Template.CreateFormat()
.Arg(this, nameof(Page), s => s.Page)
.Arg(this, nameof(TotalPages), s => s.TotalPages)
.Build();
}
Bind it in XAML like any other Lingua observable:
<TextBlock Text="{Binding PageText^}" />
Build() composes the chain into the final observable (a LinguaFormatObservable, itself an IObservable<string?>), which additionally exposes Refresh(): it re-reads every pull-based argument (live properties and computed getters), recomputes with the manager's current culture, and notifies subscribers even when the result is unchanged โ handy for a refresh button:
private readonly LinguaFormatObservable _stampText =
manager.CreateFormat("Total {0}").Arg(() => _service.GetLiveTotal()).Build();
private void Refresh() => _stampText.Refresh();
Observable arguments are push-only โ Refresh() does not re-read them; constants are fixed at build time. The built observable behaves like a behavior subject: subscribing immediately emits the current formatted string, and every subsequent change re-emits a recomputed value โ whenever the format template changes, a live argument changes, or the manager's active culture changes. Formatting uses the manager's CurrentCulture, so numbers and dates follow the selected language even when the resource variant omits the template key. Notifications are serialized; updates and subscriptions initiated from an observer callback are delivered after the current notification completes.
Arg has four overloads, one per argument kind:
Arg(constant)โ a fixed value;Arg(observable)โ anyIObservable<T>; value types (e.g. ReactiveUI'sWhenAnyValue) are boxed automatically, no adaptation needed;Arg(source, propertyName, getter)โ a live property: the combiner subscribes the source'sPropertyChangedevent directly and re-reads the property through the getter delegate โ no reflection, no expression trees, keeping it trimmer- and NativeAOT-friendly. Setting a property to its current value does not re-emit (identical formatted results are suppressed), andPropertyChangedevents with an empty ornullname are honored as "all properties may have changed";Arg(getter)โ a computed, read-on-demand value: read once on first subscription and on everyRefresh(). The source does not need to implementINotifyPropertyChangedโ use it for plain properties or external state without change notifications.
For a custom or constant template, start the chain from the manager with CreateFormat instead:
LinguaManager.Instance.CreateFormat("Page {0} of {1}")
.Arg(this, nameof(Page), s => s.Page)
.Build();
CreateFormat also accepts an IObservable<string?> template source (e.g. LinguaObservableString.FromLiteral or a template composed at runtime). For templates that come from the manager's own resources, use Keys.X.CreateFormat() to start directly from the resource key.
CulturePicker โ built-in culture switcher
CulturePicker is a TemplatedControl that provides a ready-to-use ComboBox for switching cultures.
It drives one or more ILinguaManager instances and exposes a CultureChanged routed event.
Important: The control's template is defined in
Themes/Generic.axaml. You must include the theme style in yourApp.axaml, otherwise the picker will appear blank:<Application.Styles> <StyleInclude Source="avares://Irihi.Lingua.Core/Themes/Generic.axaml" /> </Application.Styles>
XAML with binding
<Window xmlns="https://github.com/avaloniaui"
xmlns:lingua="https://irihi.tech/lingua">
<lingua:CulturePicker Managers="{Binding Managers}"
Cultures="{Binding Cultures}" />
</Window>
public class MainWindowViewModel
{
public IList<ILinguaManager> Managers { get; } = new List<ILinguaManager>
{
LanguageManager.Instance,
JsonLanguageManager.Instance
};
public IList<LinguaCulture> Cultures { get; } = new List<LinguaCulture>
{
new() { Culture = CultureInfo.InvariantCulture, DisplayName = "English", ShortDisplayName = "EN" },
new() { Culture = new CultureInfo("zh-Hans"), DisplayName = "Chinese (Simplified)", ShortDisplayName = "ไธญๆ" }
};
}
XAML inline definition
Cultures can also be defined directly in XAML โ LinguaCulture has a [Content] property and a TypeConverter so you can write culture names as inner text:
<lingua:CulturePicker Managers="{Binding Managers}">
<lingua:CulturePicker.Cultures>
<lingua:LinguaCulture DisplayName="English" ShortDisplayName="EN">en</lingua:LinguaCulture>
<lingua:LinguaCulture DisplayName="็ฎไฝไธญๆ" ShortDisplayName="ไธญๆ">zh-Hans</lingua:LinguaCulture>
</lingua:CulturePicker.Cultures>
</lingua:CulturePicker>
CultureChanged event
<lingua:CulturePicker CultureChanged="OnCultureChanged" />
private void OnCultureChanged(object? sender, CultureChangedEventArgs e)
{
Console.WriteLine($"Switched to {e.Culture?.DisplayText}");
}
| Property | Type | Description |
|---|---|---|
Managers |
IList<ILinguaManager>? |
One or more managers to drive |
Cultures |
IList<LinguaCulture>? |
Available cultures |
SelectedItem |
LinguaCulture? |
Currently selected culture |
CultureChanged |
RoutedEvent<CultureChangedEventArgs> |
Fires after selection changes |
LinguaCulture property |
Description |
|---|---|
CultureName (Content) |
Culture identifier string (e.g. "zh-Hans") |
DisplayName |
Full display name shown in dropdown |
ShortDisplayName |
Compact name shown in selection box |
DisplayText |
Read-only: DisplayName ?? NativeName |
SelectionDisplayText |
Read-only: ShortDisplayName ?? DisplayText |
Changes from Previous Version
Adoption Assessment
A verified publisher signal is available. Assess fit from the package's supported frameworks, license and dependency graph rather than popularity alone.
Related Guides & Workflows
Learn how to evaluate, integrate, or audit this package in your .NET project.