├── src ├── Avalonia │ ├── Avalonia │ │ ├── Global.cs │ │ ├── Properties │ │ │ └── AssemblyInfo.cs │ │ ├── Antelcat.I18N.Avalonia.csproj │ │ ├── Internals │ │ │ └── NotifierPropertyAccessorPlugin.cs │ │ └── I18NExtension.cs │ └── Demo │ │ ├── Models │ │ └── LangKeys.cs │ │ ├── Program.cs │ │ ├── App.axaml │ │ ├── Views │ │ ├── MainWindow.axaml.cs │ │ └── MainWindow.axaml │ │ ├── App.axaml.cs │ │ ├── ViewModels │ │ └── ViewModel.cs │ │ ├── Properties │ │ ├── Resources.zh.resx │ │ ├── Resources.resx │ │ └── Resources.Designer.cs │ │ └── Antelcat.I18N.Avalonia.Demo.csproj ├── Icon.ico ├── WPF │ ├── Library │ │ ├── Global.cs │ │ ├── Windows │ │ │ ├── MicrosoftPleaseFixAutogenWindow.cs │ │ │ ├── MainWindow.xaml.cs │ │ │ └── MainWindow.xaml │ │ ├── Models │ │ │ └── LangKeys.cs │ │ ├── Properties │ │ │ ├── AssemblyInfo.cs │ │ │ ├── Resources.zh.resx │ │ │ ├── Resources.resx │ │ │ └── Resources.Designer.cs │ │ ├── Antelcat.I18N.WPF.Library.csproj │ │ └── ViewModels │ │ │ └── ViewModel.cs │ ├── WPF │ │ ├── Properties │ │ │ └── AssemblyInfo.cs │ │ ├── Antelcat.I18N.WPF.csproj │ │ └── I18NExtension.cs │ ├── Demo.Framework │ │ ├── App.xaml.cs │ │ ├── App.xaml │ │ ├── AssemblyInfo.cs │ │ └── Antelcat.I18N.WPF.Demo.Framework.csproj │ └── Demo │ │ ├── App.xaml.cs │ │ ├── App.xaml │ │ └── Antelcat.I18N.WPF.Demo.csproj ├── Antelcat.I18N.SourceGenerators.Shared │ ├── Global.cs │ ├── Antelcat.I18N.SourceGenerators.Shared.projitems │ ├── Antelcat.I18N.SourceGenerators.Shared.shproj │ └── Generators │ │ ├── AttributeDetectBaseGenerator.cs │ │ ├── ModuleInitializerGenerator.cs │ │ └── ResourceKeysGenerator.cs ├── Antelcat.I18N.Abstractions.Shared │ ├── Attributes │ │ ├── ResourceKeysOfAttribute.cs │ │ └── DisableGenerationForAttribute.cs │ ├── Antelcat.I18N.Abstractions.Shared.projitems │ ├── Antelcat.I18N.Abstractions.Shared.shproj │ └── Abstractions │ │ └── ResourceProvider.cs ├── Antelcat.I18N.sln.DotSettings ├── Antelcat.I18N.Shared │ ├── Antelcat.I18N.Shared.projitems │ ├── Antelcat.I18N.Shared.shproj │ ├── LanguageBinding.cs │ └── I18NExtension.cs ├── SourceGenerators │ └── Antelcat.I18N.SourceGenerators.csproj ├── Antelcat.I18N.Abstractions │ └── Antelcat.I18N.Abstractions.csproj └── Antelcat.I18N.sln ├── Icon.png ├── docs ├── demo.en.png └── demo.zh.png ├── .gitattributes ├── LICENSE ├── README.md ├── README.en.md └── .gitignore /src/Avalonia/Avalonia/Global.cs: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Antelcat/I18N/HEAD/Icon.png -------------------------------------------------------------------------------- /src/Icon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Antelcat/I18N/HEAD/src/Icon.ico -------------------------------------------------------------------------------- /docs/demo.en.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Antelcat/I18N/HEAD/docs/demo.en.png -------------------------------------------------------------------------------- /docs/demo.zh.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Antelcat/I18N/HEAD/docs/demo.zh.png -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /src/WPF/Library/Global.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | using Antelcat.I18N.Attributes; 3 | 4 | -------------------------------------------------------------------------------- /src/Avalonia/Avalonia/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using Avalonia.Metadata; 2 | 3 | [assembly:XmlnsDefinition("https://github.com/avaloniaui","Avalonia.Markup.Xaml.MarkupExtensions")] -------------------------------------------------------------------------------- /src/WPF/WPF/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Windows.Markup; 2 | 3 | [assembly:XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows")] -------------------------------------------------------------------------------- /src/WPF/Library/Windows/MicrosoftPleaseFixAutogenWindow.cs: -------------------------------------------------------------------------------- 1 | namespace Antelcat.I18N.WPF.Library.Windows; 2 | 3 | public class MicrosoftPleaseFixAutogenWindow : global::Wpf.Ui.Controls.UiWindow{ } -------------------------------------------------------------------------------- /src/Antelcat.I18N.SourceGenerators.Shared/Global.cs: -------------------------------------------------------------------------------- 1 | namespace Antelcat.I18N.WPF.SourceGenerators; 2 | 3 | public static class Global 4 | { 5 | public const string Namespace = $"{nameof(Antelcat)}.{nameof(I18N)}"; 6 | } -------------------------------------------------------------------------------- /src/WPF/Library/Models/LangKeys.cs: -------------------------------------------------------------------------------- 1 | using Antelcat.I18N.Attributes; 2 | using Antelcat.I18N.WPF.Library.Properties; 3 | 4 | namespace Antelcat.I18N.WPF.Library.Models; 5 | 6 | [ResourceKeysOf(typeof(Resources))] 7 | public static partial class LangKeys; 8 | -------------------------------------------------------------------------------- /src/Antelcat.I18N.Abstractions.Shared/Attributes/ResourceKeysOfAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Antelcat.I18N.Attributes; 4 | 5 | [AttributeUsage(AttributeTargets.Class, Inherited = false)] 6 | public class ResourceKeysOfAttribute(Type resourceType) : Attribute; 7 | -------------------------------------------------------------------------------- /src/Avalonia/Demo/Models/LangKeys.cs: -------------------------------------------------------------------------------- 1 | using Antelcat.I18N.Attributes; 2 | using Antelcat.I18N.Avalonia.Demo.Properties; 3 | 4 | namespace Antelcat.I18N.Avalonia.Demo.Models; 5 | 6 | [ResourceKeysOf(typeof(Resources))] 7 | public static partial class LangKeys 8 | { 9 | 10 | } -------------------------------------------------------------------------------- /src/Avalonia/Demo/Program.cs: -------------------------------------------------------------------------------- 1 | using Antelcat.I18N.Avalonia.Demo; 2 | using Avalonia; 3 | using Avalonia.ReactiveUI; 4 | 5 | BuildAvaloniaApp() 6 | .StartWithClassicDesktopLifetime(args); 7 | 8 | static AppBuilder BuildAvaloniaApp() 9 | => AppBuilder.Configure() 10 | .UsePlatformDetect() 11 | .LogToTrace() 12 | .UseReactiveUI(); 13 | -------------------------------------------------------------------------------- /src/WPF/Demo.Framework/App.xaml.cs: -------------------------------------------------------------------------------- 1 | using System.Windows; 2 | using Antelcat.I18N.WPF.Library.Windows; 3 | 4 | namespace Antelcat.I18N.WPF.Demo 5 | { 6 | /// 7 | /// Interaction logic for App.xaml 8 | /// 9 | public partial class App 10 | { 11 | protected override void OnStartup(StartupEventArgs e) 12 | { 13 | base.OnStartup(e); 14 | new MainWindow().Show(); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Antelcat.I18N.Abstractions.Shared/Attributes/DisableGenerationForAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Antelcat.I18N.Attributes; 4 | 5 | /// 6 | /// attributes excluded in generation 7 | /// 8 | /// 9 | [AttributeUsage(AttributeTargets.Assembly)] 10 | public class DisableGenerationForAttribute(params Type[] attributeTypes) : Attribute 11 | { 12 | internal Type[] AttributeTypes => attributeTypes; 13 | } 14 | -------------------------------------------------------------------------------- /src/WPF/Demo/App.xaml.cs: -------------------------------------------------------------------------------- 1 | using System.Windows; 2 | using Antelcat.I18N.WPF.Library.Windows; 3 | 4 | namespace Antelcat.I18N.WPF.Demo 5 | { 6 | /// 7 | /// Interaction logic for App.xaml 8 | /// 9 | public partial class App : Application 10 | { 11 | protected override void OnStartup(StartupEventArgs e) 12 | { 13 | base.OnStartup(e); 14 | new MainWindow().Show(); 15 | } 16 | 17 | } 18 | } -------------------------------------------------------------------------------- /src/WPF/Library/Windows/MainWindow.xaml.cs: -------------------------------------------------------------------------------- 1 | using Antelcat.I18N.WPF.Library.ViewModels; 2 | 3 | namespace Antelcat.I18N.WPF.Library.Windows 4 | { 5 | /// 6 | /// Interaction logic for MainWindow.xaml 7 | /// 8 | public partial class MainWindow : MicrosoftPleaseFixAutogenWindow 9 | { 10 | public MainWindow() 11 | { 12 | InitializeComponent(); 13 | DataContext = new ViewModel(); 14 | } 15 | 16 | } 17 | } -------------------------------------------------------------------------------- /src/WPF/Library/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Windows; 2 | 3 | [assembly: ThemeInfo( 4 | ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located 5 | //(used if a resource is not found in the page, 6 | // or application resource dictionaries) 7 | ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located 8 | //(used if a resource is not found in the page, 9 | // app, or any theme specific resource dictionaries) 10 | )] -------------------------------------------------------------------------------- /src/Antelcat.I18N.sln.DotSettings: -------------------------------------------------------------------------------- 1 | 2 | True 3 | True -------------------------------------------------------------------------------- /src/Avalonia/Demo/App.axaml: -------------------------------------------------------------------------------- 1 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/WPF/Demo/App.xaml: -------------------------------------------------------------------------------- 1 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/WPF/Demo.Framework/App.xaml: -------------------------------------------------------------------------------- 1 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/WPF/Demo.Framework/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Windows; 2 | 3 | [assembly: ThemeInfo( 4 | ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located 5 | //(used if a resource is not found in the page, 6 | // or application resource dictionaries) 7 | ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located 8 | //(used if a resource is not found in the page, 9 | // app, or any theme specific resource dictionaries) 10 | )] 11 | -------------------------------------------------------------------------------- /src/Antelcat.I18N.Shared/Antelcat.I18N.Shared.projitems: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $(MSBuildAllProjects);$(MSBuildThisFileFullPath) 5 | true 6 | 462B56DC-C976-4B5E-AF03-3EC9B81DBDF1 7 | 8 | 9 | Antelcat.Shared.I18N 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/Antelcat.I18N.Abstractions.Shared/Antelcat.I18N.Abstractions.Shared.projitems: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $(MSBuildAllProjects);$(MSBuildThisFileFullPath) 5 | true 6 | B90BCCD4-6914-4EBE-B729-C052A7CD9655 7 | 8 | 9 | Antelcat.I18N.Abstractions.Shared 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /src/WPF/Demo/Antelcat.I18N.WPF.Demo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinExe 5 | net8.0-windows10.0.22621.0;net462 6 | 10.0.17763.0 7 | enable 8 | true 9 | 1.0.0 10 | preview 11 | 1.0.0 12 | ../../Icon.ico 13 | Antelcat 14 | Antelcat.I18N.WPF.Demo-1.0.0 15 | Antelcat.I18N.WPF.Demo 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /src/Avalonia/Demo/Views/MainWindow.axaml.cs: -------------------------------------------------------------------------------- 1 | using System.Globalization; 2 | using System.Runtime.CompilerServices; 3 | using Antelcat.I18N.Avalonia.Demo.ViewModels; 4 | using Avalonia.Controls; 5 | using Avalonia.Threading; 6 | 7 | namespace Antelcat.I18N.Avalonia.Demo.Views 8 | { 9 | public partial class MainWindow : Window 10 | { 11 | private static bool gen; 12 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 13 | public MainWindow() 14 | { 15 | InitializeComponent(); 16 | if (gen) return; 17 | gen = true; 18 | Task.Delay(2000).ContinueWith(t => 19 | { 20 | Dispatcher.UIThread.Invoke(() => 21 | { 22 | new MainWindow 23 | { 24 | DataContext = new ViewModel() 25 | }.Show(); 26 | }); 27 | }); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Antelcat.I18N.SourceGenerators.Shared/Antelcat.I18N.SourceGenerators.Shared.projitems: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $(MSBuildAllProjects);$(MSBuildThisFileFullPath) 5 | true 6 | F2E9ECDB-C9E0-408F-947C-FDC7C609575A 7 | 8 | 9 | Antelcat.Shared.I18N.SourceGenerators 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/WPF/Demo.Framework/Antelcat.I18N.WPF.Demo.Framework.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinExe 5 | net462 6 | enable 7 | enable 8 | true 9 | 1.0.0 10 | preview 11 | 1.0.0 12 | Antelcat.I18N.WPF.Demo 13 | ../../Icon.ico 14 | Antelcat 15 | Antelcat.Wpf.I18N.Demo-1.0.0 16 | Antelcat.Wpf.I18N.Demo 17 | Antelcat.Wpf.I18N.Demo 18 | Antelcat 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /src/Antelcat.I18N.Shared/Antelcat.I18N.Shared.shproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | {28F904C6-3B6D-4140-90FF-62A6BD87B0C6} 5 | 6 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /src/Antelcat.I18N.Shared/LanguageBinding.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | #if WPF 3 | using System.Windows.Data; 4 | namespace System.Windows; 5 | #elif AVALONIA 6 | using Avalonia.Data; 7 | namespace Avalonia.Markup.Xaml.MarkupExtensions; 8 | #endif 9 | 10 | /// 11 | /// It's not a binding, Just a key to get the value from the dictionary. 12 | /// 13 | public sealed class LanguageBinding : 14 | #if WPF 15 | Binding 16 | #elif AVALONIA 17 | Binding 18 | #endif 19 | { 20 | public LanguageBinding() 21 | { 22 | } 23 | 24 | public LanguageBinding(string key) 25 | { 26 | Key = key; 27 | } 28 | 29 | [DefaultValue("")] 30 | public string? Key 31 | { 32 | get => key; 33 | set 34 | { 35 | if (string.IsNullOrEmpty(value)) return; 36 | key = value; 37 | } 38 | } 39 | 40 | private string? key; 41 | 42 | #if AVALONIA 43 | /*public override object ProvideValue(IServiceProvider serviceProvider) 44 | { 45 | return this; 46 | }*/ 47 | #endif 48 | } -------------------------------------------------------------------------------- /src/Antelcat.I18N.Abstractions.Shared/Antelcat.I18N.Abstractions.Shared.shproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | {F3F24657-983C-46FF-B928-ADD03557C562} 5 | 6 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /src/Antelcat.I18N.SourceGenerators.Shared/Antelcat.I18N.SourceGenerators.Shared.shproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | {15D71DC2-F53D-42EC-85E4-4982F6E351A5} 5 | 6 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /src/Avalonia/Demo/App.axaml.cs: -------------------------------------------------------------------------------- 1 | using Antelcat.I18N.Avalonia.Demo.ViewModels; 2 | using Antelcat.I18N.Avalonia.Demo.Views; 3 | using Avalonia; 4 | using Avalonia.Controls; 5 | using Avalonia.Controls.ApplicationLifetimes; 6 | using Avalonia.Markup.Xaml; 7 | using Avalonia.Styling; 8 | 9 | namespace Antelcat.I18N.Avalonia.Demo 10 | { 11 | public partial class App : Application 12 | { 13 | public override void Initialize() 14 | { 15 | AvaloniaXamlLoader.Load(this); 16 | if (Design.IsDesignMode) 17 | { 18 | RequestedThemeVariant = ThemeVariant.Dark; 19 | } 20 | } 21 | 22 | public override void OnFrameworkInitializationCompleted() 23 | { 24 | if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) 25 | { 26 | desktop.MainWindow = new MainWindow 27 | { 28 | DataContext = new ViewModel(), 29 | }; 30 | } 31 | 32 | base.OnFrameworkInitializationCompleted(); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Feast 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/Avalonia/Demo/ViewModels/ViewModel.cs: -------------------------------------------------------------------------------- 1 | using System.Globalization; 2 | using System.Reflection; 3 | using Antelcat.I18N.Avalonia.Demo.Models; 4 | using Avalonia.Markup.Xaml.MarkupExtensions; 5 | using CommunityToolkit.Mvvm.ComponentModel; 6 | 7 | namespace Antelcat.I18N.Avalonia.Demo.ViewModels; 8 | 9 | public partial class ViewModel : ObservableObject 10 | { 11 | public ViewModel() 12 | { 13 | selectedKey = AvailableKeys.FirstOrDefault(); 14 | InputText = AvailableKeys.FirstOrDefault(); 15 | } 16 | public CultureInfo Culture 17 | { 18 | get => culture; 19 | set 20 | { 21 | if (culture.EnglishName.Equals(value.EnglishName)) return; 22 | culture = value; 23 | I18NExtension.Culture = value; 24 | } 25 | } 26 | 27 | private static CultureInfo culture = new("zh"); 28 | 29 | public IList AvailableCultures { get; } = new List 30 | { 31 | new("zh"), 32 | new("en") 33 | }; 34 | 35 | public IList AvailableKeys { get; } = 36 | new LangKeys.__ResourcesProvider().Keys() 37 | .ToList(); 38 | 39 | [ObservableProperty] private string? selectedKey; 40 | 41 | [ObservableProperty] private string? inputText; 42 | } 43 | -------------------------------------------------------------------------------- /src/Antelcat.I18N.Abstractions.Shared/Abstractions/ResourceProvider.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Collections.ObjectModel; 3 | using System.ComponentModel; 4 | using System.Data; 5 | using System.Globalization; 6 | using System.Runtime.CompilerServices; 7 | 8 | namespace Antelcat.I18N.Abstractions; 9 | 10 | public abstract class ResourceProvider : INotifyPropertyChanged 11 | { 12 | internal static readonly ObservableCollection Providers = new(); 13 | 14 | public abstract string this[string key] { get; } 15 | 16 | public abstract IEnumerable Keys(); 17 | 18 | protected static void RegisterProvider(ResourceProvider provider) 19 | { 20 | lock (Providers) 21 | { 22 | if (Providers.Contains(provider)) return; 23 | Providers.Add(provider); 24 | } 25 | } 26 | 27 | public event PropertyChangedEventHandler? PropertyChanged; 28 | 29 | public event StatementCompletedEventHandler? ChangeCompleted; 30 | 31 | protected void OnPropertyChanged( 32 | #if NET45_OR_GREATER || NET || NETSTANDARD 33 | [CallerMemberName] 34 | #endif 35 | string? propertyName = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 36 | 37 | 38 | protected void OnChangeCompleted() => ChangeCompleted?.Invoke(this, null); 39 | 40 | public abstract CultureInfo? Culture { get; set; } 41 | } -------------------------------------------------------------------------------- /src/WPF/Library/Antelcat.I18N.WPF.Library.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Library 5 | net462;net7.0-windows 6 | enable 7 | true 8 | Antelcat.I18N.WPF.Library 9 | preview 10 | 11 | 12 | 13 | 14 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | PublicResXFileCodeGenerator 26 | Resources.Designer.cs 27 | 28 | 29 | Resources.resx 30 | PublicResXFileCodeGenerator 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /src/WPF/Library/ViewModels/ViewModel.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Globalization; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Windows; 6 | using Antelcat.I18N.WPF.Library.Models; 7 | using CommunityToolkit.Mvvm.ComponentModel; 8 | 9 | namespace Antelcat.I18N.WPF.Library.ViewModels; 10 | 11 | public partial class ViewModel : ObservableObject 12 | { 13 | public ViewModel() 14 | { 15 | selectedKey = AvailableKeys.FirstOrDefault(); 16 | InputText = AvailableKeys.FirstOrDefault(); 17 | } 18 | public CultureInfo Culture 19 | { 20 | get => culture; 21 | set 22 | { 23 | if (culture.EnglishName.Equals(value.EnglishName)) return; 24 | culture = value; 25 | I18NExtension.Culture = value; 26 | OnPropertyChanged(); 27 | } 28 | } 29 | 30 | private CultureInfo culture = new("zh"); 31 | 32 | public IList AvailableCultures { get; } = new List 33 | { 34 | new("zh"), 35 | new("en") 36 | }; 37 | 38 | public IEnumerable AvailableKeys { get; } = 39 | typeof(LangKeys) 40 | .GetProperties(BindingFlags.Static | BindingFlags.Public) 41 | .Select(x => x.Name) 42 | .ToList(); 43 | 44 | [ObservableProperty] private string? selectedKey; 45 | 46 | [ObservableProperty] private string? inputText; 47 | } 48 | -------------------------------------------------------------------------------- /src/SourceGenerators/Antelcat.I18N.SourceGenerators.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | false 6 | enable 7 | preview 8 | 9 | true 10 | true 11 | 12 | Antelcat.I18N.SourceGenerators 13 | Antelcat.I18N.SourceGenerators 14 | true 15 | 1.0.0 16 | 1.0.0 17 | 1.0.0 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /src/WPF/Library/Properties/Resources.zh.resx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | text/microsoft-resx 11 | 12 | 13 | 1.3 14 | 15 | 16 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 17 | 18 | 19 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 20 | 21 | 22 | 语言 23 | 24 | 25 | 英文 26 | 27 | 28 | 中文 29 | 30 | 31 | 当前的{0}是 {1} 32 | 33 | 34 | 选择你需要翻译的文本 35 | 36 | 37 | 翻译后的文本 38 | 39 | 40 | 可用的语言 41 | 42 | 43 | 输入你需要翻译的文本 44 | 45 | -------------------------------------------------------------------------------- /src/Avalonia/Demo/Properties/Resources.zh.resx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | text/microsoft-resx 11 | 12 | 13 | 1.3 14 | 15 | 16 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 17 | 18 | 19 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 20 | 21 | 22 | 语言 23 | 24 | 25 | 英文 26 | 27 | 28 | 中文 29 | 30 | 31 | 当前的{0}是 {1} 32 | 33 | 34 | 选择你需要翻译的文本 35 | 36 | 37 | 翻译后的文本 38 | 39 | 40 | 可用的语言 41 | 42 | 43 | 输入你需要翻译的文本 44 | 45 | -------------------------------------------------------------------------------- /src/WPF/Library/Properties/Resources.resx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | text/microsoft-resx 11 | 12 | 13 | 1.3 14 | 15 | 16 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 17 | 18 | 19 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 20 | 21 | 22 | Language 23 | 24 | 25 | English 26 | 27 | 28 | Chinese 29 | 30 | 31 | Current {0} is {1} 32 | 33 | 34 | Select your text to translate 35 | 36 | 37 | Translated text 38 | 39 | 40 | Available languages 41 | 42 | 43 | Input your text to translate 44 | 45 | -------------------------------------------------------------------------------- /src/Avalonia/Demo/Properties/Resources.resx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | text/microsoft-resx 11 | 12 | 13 | 1.3 14 | 15 | 16 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 17 | 18 | 19 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 20 | 21 | 22 | Language 23 | 24 | 25 | English 26 | 27 | 28 | Chinese 29 | 30 | 31 | Current {0} is {1} 32 | 33 | 34 | Select your text to translate 35 | 36 | 37 | Translated text 38 | 39 | 40 | Available languages 41 | 42 | 43 | Input your text to translate 44 | 45 | -------------------------------------------------------------------------------- /src/Antelcat.I18N.SourceGenerators.Shared/Generators/AttributeDetectBaseGenerator.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Immutable; 2 | using System.Diagnostics; 3 | using Microsoft.CodeAnalysis; 4 | using Microsoft.CodeAnalysis.CSharp; 5 | using Microsoft.CodeAnalysis.CSharp.Syntax; 6 | 7 | namespace Antelcat.I18N.WPF.SourceGenerators.Generators; 8 | 9 | internal abstract class AttributeDetectBaseGenerator : IIncrementalGenerator 10 | { 11 | protected abstract string AttributeName { get; } 12 | 13 | public void Initialize(IncrementalGeneratorInitializationContext context) 14 | { 15 | try 16 | { 17 | var info = context.SyntaxProvider.ForAttributeWithMetadataName( 18 | AttributeName, 19 | static (node, _) => 20 | node is ClassDeclarationSyntax { Parent: not ClassDeclarationSyntax } classDeclarationSyntax 21 | && classDeclarationSyntax.Modifiers.Any(SyntaxKind.PartialKeyword), 22 | (ctx, token) => 23 | { 24 | var node = ctx.TargetNode as ClassDeclarationSyntax; 25 | var attribute = node.GetSpecifiedAttribute(ctx.SemanticModel, AttributeName, token); 26 | if (attribute == null) return (ctx, null); 27 | var argumentSyntax = attribute.ArgumentList?.Arguments.FirstOrDefault(); 28 | return argumentSyntax is not { Expression: TypeOfExpressionSyntax typeOfExp } 29 | ? (ctx, null) 30 | : (ctx, typeOfExp.Type); 31 | } 32 | ).Where(x => x.Type != null); 33 | 34 | context.RegisterSourceOutput(info.Collect(), GenerateCode); 35 | } 36 | catch (System.Exception e) 37 | { 38 | Debugger.Launch(); 39 | throw; 40 | } 41 | } 42 | 43 | protected abstract void GenerateCode(SourceProductionContext context, 44 | ImmutableArray<(GeneratorAttributeSyntaxContext, TypeSyntax)> targets); 45 | } -------------------------------------------------------------------------------- /src/Antelcat.I18N.Abstractions/Antelcat.I18N.Abstractions.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Library 5 | netstandard2.0;net40; 6 | enable 7 | enable 8 | preview 9 | 10 | 1.1.0 11 | 1.1.0 12 | 1.1.0 13 | 14 | Antelcat 15 | icon.png 16 | Antelcat.I18N.SourceGenerators 17 | Antelcat.I18N.SourceGenerators 18 | Antelcat.I18N.SourceGenerators 19 | true 20 | Initial release 21 | Copyright Antelcat. All rights reserved 22 | true 23 | dotnet;Avalonia;WPF;markup;extension;MVVM;i18n;language;binding;.NET;SourceGenerator; 24 | Auto generate provider code for Antelcat.I18N 25 | 26 | git 27 | MIT 28 | https://github.com/Antelcat/Antelcat.I18N.git 29 | https://github.com/Antelcat/Antelcat.I18N 30 | 31 | README.md 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /src/WPF/WPF/Antelcat.I18N.WPF.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | net40; 6 | net5.0-windows; 7 | 8 | enable 9 | enable 10 | true 11 | true 12 | preview 13 | 14 | 1.1.0 15 | 1.1.0 16 | 1.1.0 17 | 18 | Antelcat 19 | Antelcat.I18N.WPF 20 | Antelcat.I18N.WPF 21 | Antelcat.I18N.WPF 22 | true 23 | Fix string template using args of none string type 24 | Copyright Antelcat. All rights reserved 25 | true 26 | dotnet;WPF;markup;extension;MVVM;i18n;language;binding;.NET; 27 | Reactive language support for WPF applications when using .resx translate file. 28 | 29 | git 30 | MIT 31 | https://github.com/Antelcat/Antelcat.I18N.git 32 | https://github.com/Antelcat/Antelcat.I18N 33 | 34 | Icon.png 35 | README.md 36 | 37 | WPF 38 | 39 | 40 | 41 | 42 | 43 | README.md 44 | 45 | 46 | Icon.png 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /src/Avalonia/Avalonia/Antelcat.I18N.Avalonia.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.1 5 | enable 6 | enable 7 | true 8 | preview 9 | 10 | 1.1.2 11 | 1.1.2 12 | 1.1.2 13 | 14 | Antelcat 15 | Antelcat.I18N.Avalonia 16 | Antelcat.I18N.Avalonia 17 | Antelcat.I18N.Avalonia 18 | true 19 | hook avalonia window lifetime & supress key not found 20 | Copyright Antelcat. All rights reserved 21 | true 22 | dotnet;Avalonia;markup;extension;MVVM;i18n;language;binding;.NET; 23 | Reactive language support for Avalonia applications when using .resx translate file. 24 | 25 | git 26 | MIT 27 | https://github.com/Antelcat/Antelcat.I18N.git 28 | https://github.com/Antelcat/Antelcat.I18N 29 | 30 | Icon.png 31 | README.md 32 | 33 | AVALONIA 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | True 43 | \ 44 | 45 | 46 | True 47 | 48 | Icon.png 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /src/Avalonia/Avalonia/Internals/NotifierPropertyAccessorPlugin.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using System.Diagnostics.CodeAnalysis; 3 | using Avalonia.Data; 4 | using Avalonia.Data.Core.Plugins; 5 | using Avalonia.Markup.Xaml.MarkupExtensions; 6 | 7 | namespace Antelcat.I18N.Avalonia.Internals; 8 | 9 | internal class NotifierPropertyAccessorPlugin 10 | : IPropertyAccessorPlugin 11 | { 12 | [field: MaybeNull, AllowNull] 13 | internal static IPropertyAccessorPlugin Instance 14 | { 15 | get 16 | { 17 | if (field is not null) return field; 18 | field = new NotifierPropertyAccessorPlugin(); 19 | return field; 20 | } 21 | } 22 | 23 | public bool Match(object obj, string propertyName) => 24 | propertyName is nameof(I18NExtension.ResourceChangedNotifier.Source) && 25 | obj is I18NExtension.ResourceChangedNotifier; 26 | 27 | 28 | public IPropertyAccessor? Start(WeakReference reference, string propertyName) => 29 | reference.TryGetTarget(out var t) 30 | && t is I18NExtension.ResourceChangedNotifier n 31 | ? new NotifyAccessor(n) 32 | : null; 33 | 34 | 35 | private class NotifyAccessor : IPropertyAccessor 36 | { 37 | private readonly I18NExtension.ResourceChangedNotifier notifier; 38 | public NotifyAccessor(I18NExtension.ResourceChangedNotifier notifier) 39 | { 40 | this.notifier = notifier; 41 | this.notifier.PropertyChanged += OnPropertyChanged; 42 | } 43 | private event Action? Subscriptions; 44 | 45 | private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) 46 | { 47 | if (Subscriptions is null) return; 48 | Subscriptions(null); 49 | Subscriptions(Value); 50 | } 51 | 52 | ~NotifyAccessor() => Dispose(); 53 | 54 | public void Dispose() => Unsubscribe(); 55 | 56 | public bool SetValue(object? value, BindingPriority priority) => throw new NotImplementedException(); 57 | 58 | public void Subscribe(Action listener) => Subscriptions += listener; 59 | 60 | public void Unsubscribe() 61 | { 62 | Subscriptions = null; 63 | notifier.PropertyChanged -= OnPropertyChanged; 64 | Console.WriteLine("Unsub"); 65 | } 66 | 67 | public Type? PropertyType { get; } = typeof(INotifyPropertyChanged); 68 | public object? Value => notifier.Source; 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/Avalonia/Demo/Antelcat.I18N.Avalonia.Demo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinExe 5 | net8.0 6 | enable 7 | enable 8 | copyused 9 | true 10 | 1.0.0 11 | 1.0.0 12 | Antelcat 13 | Antelcat.Avalonia.I18N.Demo-1.0.0 14 | ..\..\Icon.ico 15 | true 16 | 17 | 18 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 37 | 38 | 39 | 40 | 41 | ResXFileCodeGenerator 42 | Resources.Designer.cs 43 | 44 | 45 | Resources.resx 46 | 47 | 48 | 49 | 50 | True 51 | True 52 | Resources.resx 53 | 54 | 55 | 56 | 57 | Icon.ico 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /src/Antelcat.I18N.SourceGenerators.Shared/Generators/ModuleInitializerGenerator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using System.Runtime.CompilerServices; 6 | using System.Text; 7 | using Antelcat.I18N.Attributes; 8 | using Microsoft.CodeAnalysis; 9 | using Microsoft.CodeAnalysis.CSharp.Syntax; 10 | using Microsoft.CodeAnalysis.Text; 11 | 12 | namespace Antelcat.I18N.WPF.SourceGenerators.Generators; 13 | 14 | [Generator] 15 | public class ModuleInitializerGenerator : IIncrementalGenerator 16 | { 17 | public void Initialize(IncrementalGeneratorInitializationContext context) 18 | { 19 | var provider = context.SyntaxProvider.CreateSyntaxProvider( 20 | (c,t)=>c is ClassDeclarationSyntax, 21 | (c, t) => 22 | { 23 | var symbol = c.SemanticModel.GetDeclaredSymbol(c.Node); 24 | if (symbol is not INamedTypeSymbol type) return null; 25 | if (type.TypeKind != TypeKind.Class) return null; 26 | while (type.BaseType != null) type = type.BaseType; 27 | return type; 28 | }); 29 | var disable = context.SyntaxProvider 30 | .ForAttributeWithMetadataName( 31 | typeof(DisableGenerationForAttribute).FullName!, 32 | (_, _) => true, 33 | (c, _) => c); 34 | context.RegisterSourceOutput(provider.Collect().Combine(disable.Collect()), (ctx, objs) => 35 | { 36 | Dictionary generates = new() 37 | { 38 | { 39 | "global::" + typeof(ModuleInitializerAttribute).FullName, 40 | ("ModuleInitializerAttribute.g.cs", 41 | """ 42 | namespace System.Runtime.CompilerServices 43 | { 44 | [global::System.AttributeUsage(AttributeTargets.Method, Inherited = false)] 45 | internal class ModuleInitializerAttribute : Attribute { } 46 | } 47 | """) 48 | } 49 | }; 50 | 51 | 52 | 53 | var obj = objs.Left.FirstOrDefault(x => x != null); 54 | if (obj is null) return; 55 | var version = obj.ContainingAssembly.Identity.Version; 56 | if (version.CompareTo(new Version(3, 5)) < 0 57 | || version.CompareTo(new Version(5, 0)) >= 0) return; 58 | 59 | if (objs.Right.Any()) 60 | { 61 | var disGen = objs.Right 62 | .First().Attributes 63 | .FirstOrDefault()? 64 | .ConstructorArguments.FirstOrDefault(); 65 | if (disGen is not null) 66 | { 67 | foreach (var typeName in from TypedConstant constant in disGen.Value.Values 68 | select (constant.Value as INamedTypeSymbol).GetFullyQualifiedName()) 69 | { 70 | generates.Remove(typeName); 71 | } 72 | } 73 | } 74 | 75 | foreach (var pair in generates) 76 | { 77 | ctx.AddSource(pair.Value.fileName, SourceText.From(pair.Value.content, Encoding.UTF8)); 78 | } 79 | }); 80 | } 81 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

4 | 5 | Antelcat.`{I18N}` 6 | 7 |

8 | 9 | 给.NET应用程序提供响应式的多语言支持。 10 | 11 |
12 | 13 |

14 | dotnet-version 15 | dotnet-version 16 | csharp-version 17 | nuget 18 |

19 | 20 | --- 21 | 22 | 🇬🇧 [English](./README.en.md) 23 | 24 | ## 🗔 受支持的平台 25 | 26 | + [WPF](https://github.com/dotnet/wpf) 27 | + [Avalonia](https://github.com/AvaloniaUI/Avalonia) 28 | 29 | ## 📖 示例 30 | 31 |
32 | 33 | 34 |
35 | 36 | --- 37 | 38 | ### 静态使用 39 | 40 | 当你在项目中使用`.resx`文件作为语言文件时,你可以使用`Antelcat.I18N.Attributes.ResourceKeysOfAttribute`来自动生成资源键: 41 | 42 | ```csharp 43 | using Antelcat.I18N.Attributes; 44 | 45 | namespace MyProject 46 | 47 | //Auto generated class should be partial 48 | [ResourceKeysOf(typeof(My.Resource.Designer.Type))] 49 | public partial class LangKeys 50 | { 51 | } 52 | ``` 53 | 54 | 然后在你的`.xaml`文件中使用`x:Static`来为你的控件提供资源键 55 | 56 | 如果你已经在你的`.resx`文件中有 57 | 58 | ```xml 59 | 60 | 61 | 语言 62 | 63 | ``` 64 | 65 | 你可以像这样使用: 66 | 67 | ```xaml 68 | 69 | ``` 70 | 71 | 然后你可以使用这个键来绑定语言源 72 | 73 | ```xaml 74 | 75 | ``` 76 | 77 | 当你想要改变语言时,只需要调用 78 | 79 | ```csharp 80 | using System.Windows; 81 | 82 | I18NExtension.Culture = new CultureInfo("language code"); 83 | ``` 84 | 85 | 你可以看到文本在语言之间变化。 86 | 87 | --- 88 | 89 | ### 动态使用 90 | 91 | 有时你的源文本并不是在你的应用程序中定义的,而是从其他来源(如网络)接收到的,你可以使用`I18N`直接绑定文本。 92 | 93 | 如果你收到了一个像这样的json: 94 | 95 | ```json 96 | { 97 | "message": "This is a message" 98 | } 99 | ``` 100 | 101 | 并且你已经在`.resx`中将他翻译成了另一种语言 102 | 103 | ```xml 104 | 105 | 106 | 这是一条消息 107 | 108 | ``` 109 | 110 | 你肯定会设计一个`ViewModel`并且将他设置到属性`Message`中,你可以像这样绑定: 111 | 112 | ```xaml 113 | 114 | 115 | ``` 116 | 117 | 每当`Message`属性被改变或者语言源被改变时,文本都会自动更新。 118 | 119 | --- 120 | 121 | ### 多个文本组合和格式化 122 | 123 | 有些情况下,你需要将多个文本组合起来,或者对文本进行格式化,你可以使用`I18N`和`LanguageBinding`来实现。 124 | 125 | 如果你已经有了如下翻译的`.resx`文件: 126 | 127 | ```xml 128 | 129 | 130 | 当前的 {0} 是 {1} 131 | 132 | 133 | 语言 134 | 135 | 136 | 中文 137 | 138 | ``` 139 | 140 | 并且在`.xaml`中 141 | 142 | ```xaml 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | ``` 152 | 153 | 此时 `I18N.Key` 是字符串的模板,其中的 `LanguageBinding` 和 `Binding` 会提供模板的参数,他们会被按顺序格式化成最终的文本。同时保持整体的响应性。 -------------------------------------------------------------------------------- /README.en.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

4 | 5 | Antelcat.`{I18N}` 6 | 7 |

8 | 9 | Reactive language support for .NET applications. 10 | 11 |
12 | 13 |

14 | dotnet-version 15 | dotnet-version 16 | csharp-version 17 | nuget 18 |

19 | 20 | --- 21 | 22 | 🇨🇳 [中文版](./README.md) 23 | 24 | ## 🗔 Supported Platforms 25 | 26 | + [WPF](https://github.com/dotnet/wpf) 27 | + [Avalonia](https://github.com/AvaloniaUI/Avalonia) 28 | 29 | ## 📖 Sample 30 | 31 |
32 | 33 | 34 |
35 | 36 | 37 | ### Static using 38 | When using `.resx` language file in your project, you can 39 | automatically generate resource keys by using `Antelcat.I18N.Attributes.ResourceKeysOfAttribute`: 40 | 41 | ```csharp 42 | using Antelcat.I18N.Attributes; 43 | 44 | namespace MyProject 45 | 46 | //Auto generated class should be partial 47 | [ResourceKeysOf(typeof(My.Resource.Designer.Type))] 48 | public partial class LangKeys 49 | { 50 | } 51 | ``` 52 | 53 | Then in your `.xaml` file you can use `x:Static` to provide resource key to your control 54 | 55 | if you already have 56 | ```xml 57 | 58 | Language 59 | 60 | ``` 61 | in your `.resx` file, you can use it like this: 62 | ```xaml 63 | 64 | ``` 65 | 66 | Then you can use the key to bind the language source using `I18N` 67 | 68 | ```xaml 69 | 70 | ``` 71 | 72 | When you want to change the language, just call 73 | 74 | ```csharp 75 | using System.Windows; 76 | 77 | I18NExtension.Culture = new CultureInfo("language code"); 78 | ``` 79 | You can see the text is changing among the languages. 80 | 81 | --- 82 | 83 | ### Dynamic using 84 | 85 | Sometimes your source text is not defined in your application but received from other source like network, you can use `I18N` to bind the text directly. 86 | 87 | If you receive a json like this: 88 | ```json 89 | { 90 | "message": "This is a message" 91 | } 92 | ``` 93 | and you have translated it into another language in `.resx` like 94 | ```xml 95 | 96 | 这是一条消息 97 | 98 | ``` 99 | 100 | then you put the json into a `Message` property in your view model, you can bind it like this: 101 | 102 | ```xaml 103 | 104 | 105 | ``` 106 | 107 | Each time when the `Message` property is changed or the language source is changed, the text will be updated automatically. 108 | 109 | --- 110 | 111 | ### Combination and StringFormat 112 | 113 | Somebody may want to combine several language sources into one text, you can also use `I18N` and `LanguageBinding` to do this 114 | 115 | If you have source text in `.resx` file like this: 116 | ```xml 117 | 118 | 当前的 {0} 是 {1} 119 | 120 | 121 | 语言 122 | 123 | 124 | 中文 125 | 126 | ``` 127 | 128 | and in `.xaml` 129 | 130 | ```xaml 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | ``` 140 | 141 | `I18N.Key` is the `string` template, content accepts `LanguageBinding` and `Binding` to provide the args. -------------------------------------------------------------------------------- /src/Avalonia/Avalonia/I18NExtension.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.ObjectModel; 2 | using System.Collections.Specialized; 3 | using System.ComponentModel; 4 | using System.Diagnostics; 5 | using Antelcat.I18N.Avalonia.Internals; 6 | using Avalonia.Controls; 7 | using Avalonia.Data; 8 | using Avalonia.Data.Core.Plugins; 9 | using Avalonia.Markup.Xaml.XamlIl.Runtime; 10 | using Avalonia.Metadata; 11 | using EventArgs = System.EventArgs; 12 | using ResourceProvider = Antelcat.I18N.Abstractions.ResourceProvider; 13 | 14 | namespace Avalonia.Markup.Xaml.MarkupExtensions; 15 | 16 | public partial class I18NExtension 17 | { 18 | public I18NExtension() { } 19 | 20 | static I18NExtension() 21 | { 22 | var target = new LanguageDictionary(); 23 | Target = target; 24 | Notifier = new ResourceChangedNotifier(target); 25 | SourceBinding = new(nameof(ResourceChangedNotifier.Source)) 26 | { 27 | Source = Notifier, 28 | Mode = BindingMode.OneWay, 29 | }; 30 | 31 | BindingPlugins.PropertyAccessors.Insert(0, NotifierPropertyAccessorPlugin.Instance); 32 | 33 | lock (ResourceProvider.Providers) 34 | { 35 | foreach (var provider in ResourceProvider.Providers) RegisterLanguageSource(provider); 36 | 37 | ResourceProvider.Providers.CollectionChanged += (_, e) => 38 | { 39 | if (e.Action != NotifyCollectionChangedAction.Add) return; 40 | foreach (var provider in e.NewItems.OfType()) 41 | { 42 | RegisterLanguageSource(provider); 43 | } 44 | }; 45 | } 46 | } 47 | 48 | private readonly AvaloniaObject proxy = new(); 49 | private static readonly List windows = []; 50 | 51 | #region Target 52 | 53 | private static readonly AvaloniaProperty KeyProperty = AvaloniaProperty.RegisterAttached 54 | (nameof(Key)); 55 | 56 | #endregion 57 | 58 | /// 59 | /// The args of , accepts or 60 | /// 61 | [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] 62 | [DefaultValue(null)] 63 | [Content] 64 | public Collection Keys { get; } = []; 65 | 66 | 67 | public override partial object ProvideValue(IServiceProvider serviceProvider) 68 | { 69 | if (serviceProvider.GetService(typeof(IProvideValueTarget)) is not IProvideValueTarget) 70 | return this; 71 | 72 | CheckArgument(); 73 | try 74 | { 75 | return CreateBinding(); 76 | } 77 | finally 78 | { 79 | if (serviceProvider.GetService(typeof(IAvaloniaXamlIlParentStackProvider 80 | )) is IAvaloniaXamlIlParentStackProvider 81 | 82 | { 83 | Parents: { } stack 84 | }) 85 | { 86 | if (stack.FirstOrDefault() is StyledElement control) 87 | { 88 | void Initialized(object _, EventArgs __) 89 | { 90 | Notifier.ForceUpdate(); 91 | control.Initialized -= Initialized; 92 | } 93 | 94 | control.Initialized += Initialized; 95 | } 96 | } 97 | 98 | } 99 | } 100 | 101 | private static MultiBinding CreateMultiBinding() => 102 | new() 103 | { 104 | Mode = BindingMode.OneWay, 105 | Priority = BindingPriority.LocalValue, 106 | Bindings = { SourceBinding } 107 | }; 108 | 109 | 110 | private static partial void RegisterCultureChanged(ResourceProvider provider) 111 | { 112 | CultureChanged += culture => 113 | { 114 | provider.Culture = culture; 115 | }; 116 | } 117 | 118 | partial class ResourceChangedNotifier 119 | { 120 | public void ForceUpdate() => OnPropertyChanged(nameof(Source)); 121 | } 122 | 123 | } -------------------------------------------------------------------------------- /src/Avalonia/Demo/Properties/Resources.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // 此代码由工具生成。 4 | // 运行时版本:4.0.30319.42000 5 | // 6 | // 对此文件的更改可能会导致不正确的行为,并且如果 7 | // 重新生成代码,这些更改将会丢失。 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace Antelcat.I18N.Avalonia.Demo.Properties { 12 | /// 13 | /// 一个强类型的资源类,用于查找本地化的字符串等。 14 | /// 15 | // 此类是由 StronglyTypedResourceBuilder 16 | // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 17 | // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen 18 | // (以 /str 作为命令选项),或重新生成 VS 项目。 19 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] 20 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 21 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 22 | internal class Resources { 23 | 24 | private static global::System.Resources.ResourceManager resourceMan; 25 | 26 | private static global::System.Globalization.CultureInfo resourceCulture; 27 | 28 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] 29 | internal Resources() { 30 | } 31 | 32 | /// 33 | /// 返回此类使用的缓存的 ResourceManager 实例。 34 | /// 35 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 36 | internal static global::System.Resources.ResourceManager ResourceManager { 37 | get { 38 | if (object.ReferenceEquals(resourceMan, null)) { 39 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Antelcat.I18N.Avalonia.Demo.Properties.Resources", typeof(Resources).Assembly); 40 | resourceMan = temp; 41 | } 42 | return resourceMan; 43 | } 44 | } 45 | 46 | /// 47 | /// 重写当前线程的 CurrentUICulture 属性,对 48 | /// 使用此强类型资源类的所有资源查找执行重写。 49 | /// 50 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 51 | internal static global::System.Globalization.CultureInfo Culture { 52 | get { 53 | return resourceCulture; 54 | } 55 | set { 56 | resourceCulture = value; 57 | } 58 | } 59 | 60 | /// 61 | /// 查找类似 Available languages 的本地化字符串。 62 | /// 63 | internal static string Available_languages { 64 | get { 65 | return ResourceManager.GetString("Available languages", resourceCulture); 66 | } 67 | } 68 | 69 | /// 70 | /// 查找类似 Chinese 的本地化字符串。 71 | /// 72 | internal static string Chinese { 73 | get { 74 | return ResourceManager.GetString("Chinese", resourceCulture); 75 | } 76 | } 77 | 78 | /// 79 | /// 查找类似 Current {0} is {1} 的本地化字符串。 80 | /// 81 | internal static string Current_language_is { 82 | get { 83 | return ResourceManager.GetString("Current language is", resourceCulture); 84 | } 85 | } 86 | 87 | /// 88 | /// 查找类似 English 的本地化字符串。 89 | /// 90 | internal static string English { 91 | get { 92 | return ResourceManager.GetString("English", resourceCulture); 93 | } 94 | } 95 | 96 | /// 97 | /// 查找类似 Input your text to translate 的本地化字符串。 98 | /// 99 | internal static string Input_your_text_to_translate { 100 | get { 101 | return ResourceManager.GetString("Input your text to translate", resourceCulture); 102 | } 103 | } 104 | 105 | /// 106 | /// 查找类似 Language 的本地化字符串。 107 | /// 108 | internal static string Language { 109 | get { 110 | return ResourceManager.GetString("Language", resourceCulture); 111 | } 112 | } 113 | 114 | /// 115 | /// 查找类似 Select your text to translate 的本地化字符串。 116 | /// 117 | internal static string Select_your_text_to_translate { 118 | get { 119 | return ResourceManager.GetString("Select your text to translate", resourceCulture); 120 | } 121 | } 122 | 123 | /// 124 | /// 查找类似 Translated text 的本地化字符串。 125 | /// 126 | internal static string Translated_text { 127 | get { 128 | return ResourceManager.GetString("Translated text", resourceCulture); 129 | } 130 | } 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /src/WPF/Library/Properties/Resources.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // 5 | // Changes to this file may cause incorrect behavior and will be lost if 6 | // the code is regenerated. 7 | // 8 | //------------------------------------------------------------------------------ 9 | 10 | namespace Antelcat.I18N.WPF.Library.Properties { 11 | /// 12 | /// A strongly-typed resource class, for looking up localized strings, etc. 13 | /// 14 | // This class was auto-generated by the StronglyTypedResourceBuilder 15 | // class via a tool like ResGen or Visual Studio. 16 | // To add or remove a member, edit your .ResX file then rerun ResGen 17 | // with the /str option, or rebuild your VS project. 18 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] 19 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 20 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 21 | public class Resources { 22 | 23 | private static global::System.Resources.ResourceManager resourceMan; 24 | 25 | private static global::System.Globalization.CultureInfo resourceCulture; 26 | 27 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] 28 | internal Resources() { 29 | } 30 | 31 | /// 32 | /// Returns the cached ResourceManager instance used by this class. 33 | /// 34 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 35 | public static global::System.Resources.ResourceManager ResourceManager { 36 | get { 37 | if (object.ReferenceEquals(resourceMan, null)) { 38 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Antelcat.I18N.WPF.Library.Properties.Resources", typeof(Resources).Assembly); 39 | resourceMan = temp; 40 | } 41 | return resourceMan; 42 | } 43 | } 44 | 45 | /// 46 | /// Overrides the current thread's CurrentUICulture property for all 47 | /// resource lookups using this strongly typed resource class. 48 | /// 49 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 50 | public static global::System.Globalization.CultureInfo Culture { 51 | get { 52 | return resourceCulture; 53 | } 54 | set { 55 | resourceCulture = value; 56 | } 57 | } 58 | 59 | /// 60 | /// Looks up a localized string similar to Available languages. 61 | /// 62 | public static string Available_languages { 63 | get { 64 | return ResourceManager.GetString("Available languages", resourceCulture); 65 | } 66 | } 67 | 68 | /// 69 | /// Looks up a localized string similar to Chinese. 70 | /// 71 | public static string Chinese { 72 | get { 73 | return ResourceManager.GetString("Chinese", resourceCulture); 74 | } 75 | } 76 | 77 | /// 78 | /// Looks up a localized string similar to Current {0} is {1}. 79 | /// 80 | public static string Current_language_is { 81 | get { 82 | return ResourceManager.GetString("Current language is", resourceCulture); 83 | } 84 | } 85 | 86 | /// 87 | /// Looks up a localized string similar to English. 88 | /// 89 | public static string English { 90 | get { 91 | return ResourceManager.GetString("English", resourceCulture); 92 | } 93 | } 94 | 95 | /// 96 | /// Looks up a localized string similar to Input your text to translate. 97 | /// 98 | public static string Input_your_text_to_translate { 99 | get { 100 | return ResourceManager.GetString("Input your text to translate", resourceCulture); 101 | } 102 | } 103 | 104 | /// 105 | /// Looks up a localized string similar to Language. 106 | /// 107 | public static string Language { 108 | get { 109 | return ResourceManager.GetString("Language", resourceCulture); 110 | } 111 | } 112 | 113 | /// 114 | /// Looks up a localized string similar to Select your text to translate. 115 | /// 116 | public static string Select_your_text_to_translate { 117 | get { 118 | return ResourceManager.GetString("Select your text to translate", resourceCulture); 119 | } 120 | } 121 | 122 | /// 123 | /// Looks up a localized string similar to Translated text. 124 | /// 125 | public static string Translated_text { 126 | get { 127 | return ResourceManager.GetString("Translated text", resourceCulture); 128 | } 129 | } 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /src/Avalonia/Demo/Views/MainWindow.axaml: -------------------------------------------------------------------------------- 1 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 25 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 51 | 52 | 53 | 54 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | -------------------------------------------------------------------------------- /src/WPF/WPF/I18NExtension.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Specialized; 2 | using System.ComponentModel; 3 | using System.Windows.Data; 4 | using System.Windows.Markup; 5 | using Antelcat.I18N.Abstractions; 6 | using MicrosoftPleaseFixBindingCollection = System.Collections.ObjectModel.Collection; 7 | 8 | namespace System.Windows; 9 | 10 | [MarkupExtensionReturnType(typeof(string))] 11 | [ContentProperty(nameof(Keys))] 12 | [Localizability(LocalizationCategory.None, Modifiability = Modifiability.Unmodifiable, 13 | Readability = Readability.Unreadable)] 14 | public partial class I18NExtension 15 | { 16 | public I18NExtension() 17 | { 18 | 19 | } 20 | static I18NExtension() 21 | { 22 | var target = new LanguageDictionary(); 23 | Target = target; 24 | Notifier = new ResourceChangedNotifier(target); 25 | SourceBinding = new(nameof(Notifier.Source)) 26 | { 27 | Source = Notifier, 28 | Mode = BindingMode.OneWay, 29 | }; 30 | lock (ResourceProvider.Providers) 31 | { 32 | foreach (var provider in ResourceProvider.Providers) 33 | { 34 | RegisterLanguageSource(provider); 35 | } 36 | 37 | ResourceProvider.Providers.CollectionChanged += (o, e) => 38 | { 39 | if(e.Action != NotifyCollectionChangedAction.Add)return; 40 | foreach (var provider in e.NewItems?.OfType() ?? []) 41 | { 42 | RegisterLanguageSource(provider); 43 | } 44 | }; 45 | } 46 | } 47 | 48 | private readonly DependencyObject proxy = new(); 49 | 50 | #region Target 51 | 52 | private static readonly DependencyProperty KeyProperty = DependencyProperty.RegisterAttached 53 | ( 54 | nameof(Key), 55 | typeof(object), 56 | typeof(I18NExtension), 57 | new PropertyMetadata(default) 58 | ); 59 | 60 | 61 | private static readonly DependencyProperty TargetPropertyProperty = DependencyProperty.RegisterAttached 62 | ( 63 | "TargetProperty", 64 | typeof(DependencyProperty), 65 | typeof(I18NExtension), 66 | new PropertyMetadata(default(DependencyProperty)) 67 | ); 68 | 69 | public override partial object ProvideValue(IServiceProvider serviceProvider) 70 | { 71 | if (serviceProvider.GetService(typeof(IProvideValueTarget)) is not IProvideValueTarget provideValueTarget) 72 | return this; 73 | if (provideValueTarget.TargetObject.GetType().FullName == 74 | $"{nameof(System)}.{nameof(Windows)}.SharedDp") return this; 75 | if (provideValueTarget.TargetObject is not DependencyObject targetObject) 76 | return this; 77 | 78 | if (provideValueTarget.TargetProperty is not DependencyProperty targetProperty) return this; 79 | 80 | CheckArgument(); 81 | 82 | var bindingBase = CreateBinding(); 83 | 84 | BindingOperations.SetBinding(targetObject, targetProperty, bindingBase); 85 | 86 | if (bindingBase is MultiBinding) 87 | { 88 | SetTarget(targetObject, targetProperty); 89 | } 90 | 91 | return bindingBase.ProvideValue(serviceProvider); 92 | } 93 | 94 | private static void SetTargetProperty(DependencyObject element, DependencyProperty value) 95 | => element.SetValue(TargetPropertyProperty, value); 96 | 97 | private static DependencyProperty GetTargetProperty(DependencyObject element) 98 | => (DependencyProperty)element.GetValue(TargetPropertyProperty)!; 99 | 100 | #endregion 101 | 102 | /// 103 | /// The args of , accepts or 104 | /// 105 | [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] 106 | [DefaultValue(null)] 107 | public MicrosoftPleaseFixBindingCollection Keys { get; } = []; 108 | 109 | private void I18NExtension_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) 110 | { 111 | switch (sender) 112 | { 113 | case FrameworkElement element: 114 | { 115 | element.DataContextChanged -= I18NExtension_DataContextChanged; 116 | ResetBinding(element); 117 | break; 118 | } 119 | case FrameworkContentElement element: 120 | { 121 | element.DataContextChanged -= I18NExtension_DataContextChanged; 122 | ResetBinding(element); 123 | break; 124 | } 125 | } 126 | } 127 | 128 | private void SetTarget(DependencyObject targetObject, DependencyProperty targetProperty) 129 | { 130 | switch (targetObject) 131 | { 132 | case FrameworkContentElement element: 133 | SetTargetProperty(element, targetProperty); 134 | element.DataContextChanged += I18NExtension_DataContextChanged; 135 | return; 136 | case FrameworkElement element: 137 | SetTargetProperty(element, targetProperty); 138 | element.DataContextChanged += I18NExtension_DataContextChanged; 139 | return; 140 | } 141 | } 142 | 143 | private static void SetBinding(DependencyObject element, DependencyProperty targetProperty, BindingBase binding) 144 | { 145 | BindingOperations.SetBinding(element, targetProperty, binding); 146 | } 147 | 148 | private MultiBinding CreateMultiBinding() 149 | { 150 | var ret = new MultiBinding 151 | { 152 | Mode = BindingMode.OneWay, 153 | ConverterParameter = ConverterParameter, 154 | UpdateSourceTrigger = UpdateSourceTrigger.Explicit, 155 | Bindings = { SourceBinding } 156 | }; 157 | return ret; 158 | } 159 | 160 | private void ResetBinding(DependencyObject element) 161 | { 162 | if (Key is string && !Keys.Any(x => x is not LanguageBinding)) return; 163 | var targetProperty = GetTargetProperty(element); 164 | SetTargetProperty(element, null!); 165 | var binding = CreateBinding(); 166 | SetBinding(element, targetProperty, binding); 167 | } 168 | 169 | 170 | 171 | private static partial void RegisterCultureChanged(ResourceProvider provider) 172 | { 173 | CultureChanged += culture => 174 | { 175 | provider.Culture = culture; 176 | }; 177 | } 178 | } -------------------------------------------------------------------------------- /src/WPF/Library/Windows/MainWindow.xaml: -------------------------------------------------------------------------------- 1 | 15 | 16 | 19 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | <TextBlock>\n 36 | \t<TextBlock.Text>\n 37 | \t\t<I18N Key="{x:Static m:LangKeys.Current_language_is}">\n 38 | \t\t\t<LanguageBinding Key="{x:Static m:LangKeys.Language}" />\n 39 | \t\t\t<Binding Path="Culture.EnglishName" />\n 40 | \t\t</I18N>\n 41 | \t<TextBlock.Text>\n 42 | <TextBlock> 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 59 | 60 | 61 | <TextBlock Text="{I18N {x:Static m:LangKeys.Select_your_text_to_translate}}"/> 62 | 63 | 64 | 65 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | <TextBlock Text="{I18N {x:Static m:LangKeys.Translated_text}}"/> 76 | 77 | 78 | 79 | 80 | 81 | 82 | <TextBlock Text="{I18N {Binding SelectedKey}}"/> 83 | 84 | 85 | 86 | 87 | 88 | 89 | 91 | 92 | 93 | 94 | 95 | <TextBlock Text="{I18N {Binding InputText}}"/> 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | -------------------------------------------------------------------------------- /src/Antelcat.I18N.SourceGenerators.Shared/Generators/ResourceKeysGenerator.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Immutable; 2 | using System.Globalization; 3 | using System.Linq; 4 | using System.Runtime.CompilerServices; 5 | using System.Text; 6 | using Antelcat.I18N.Abstractions; 7 | using Antelcat.I18N.Attributes; 8 | using Microsoft.CodeAnalysis; 9 | using Microsoft.CodeAnalysis.CSharp; 10 | using Microsoft.CodeAnalysis.CSharp.Syntax; 11 | using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; 12 | using GeneratorAttributeSyntaxContext = Microsoft.CodeAnalysis.GeneratorAttributeSyntaxContext; 13 | 14 | namespace Antelcat.I18N.WPF.SourceGenerators.Generators; 15 | 16 | [Generator(LanguageNames.CSharp)] 17 | internal class ResourceKeysGenerator : AttributeDetectBaseGenerator 18 | { 19 | private static readonly string Attribute = $"{typeof(ResourceKeysOfAttribute).FullName}"; 20 | private static readonly string CultureInfo = $"global::{typeof(CultureInfo).FullName}"; 21 | private static readonly string ResourceProvider = $"global::{typeof(ResourceProvider).FullName}"; 22 | private static readonly string ModuleInitializer = $"global::{typeof(ModuleInitializerAttribute).FullName}"; 23 | private static readonly string IEnumerable = $"global::{nameof(System)}.Collections.Generic.IEnumerable"; 24 | 25 | private static readonly string[] Exceptions = 26 | [ 27 | "ResourceManager", 28 | "Culture" 29 | ]; 30 | 31 | protected override string AttributeName => Attribute; 32 | 33 | protected override void GenerateCode(SourceProductionContext context, 34 | ImmutableArray<(GeneratorAttributeSyntaxContext, TypeSyntax)> targets) 35 | { 36 | foreach (var (generateCtx, type) in targets) 37 | { 38 | var targetSymbol = generateCtx.SemanticModel.GetSymbolInfo(type).Symbol as INamedTypeSymbol; 39 | var targetFullName = targetSymbol.GetFullyQualifiedName(); 40 | var names = targetSymbol! 41 | .GetMembers() 42 | .OfType() 43 | .Select(x => x.Name) 44 | .Except(Exceptions).ToList(); 45 | var nameSpace = generateCtx.TargetSymbol.ContainingNamespace.GetFullyQualifiedName(); 46 | var className = $"__{targetSymbol.Name}Provider"; 47 | var syntaxTriviaList = TriviaList( 48 | Comment("// By Antelcat.I18N.SourceGenerators"), 49 | Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true)), 50 | Trivia(NullableDirectiveTrivia(Token(SyntaxKind.EnableKeyword), true))); 51 | var unit = CompilationUnit() 52 | .AddMembers( 53 | NamespaceDeclaration(IdentifierName(nameSpace.Replace("global::", ""))) 54 | .WithLeadingTrivia(syntaxTriviaList) 55 | .AddMembers( 56 | ClassDeclaration(generateCtx.TargetSymbol.Name) 57 | .AddModifiers(Token(SyntaxKind.PartialKeyword)) 58 | .AddMembers( 59 | names.Select(x => 60 | ParseMemberDeclaration( 61 | $""" 62 | /// 63 | /// {x} 64 | /// 65 | public static string {x} => nameof({x}); 66 | """ 67 | )!) 68 | .ToArray()) 69 | .AddMembers( 70 | ClassDeclaration(className) 71 | .AddModifiers(SyntaxKind.InternalKeyword) 72 | .AddBaseListTypes(ResourceProvider) 73 | .AddMembers( 74 | ParseMemberDeclaration( 75 | $$""" 76 | public override string this[string key] { 77 | get { 78 | switch(key){ 79 | {{string.Concat(names.Select(static x=>$"case nameof({x}): return this.{x}; \n"))}} 80 | } 81 | return key; 82 | } 83 | } 84 | """ 85 | )!) 86 | .AddMembers( 87 | ParseMemberDeclaration( 88 | $$""" 89 | public override {{IEnumerable}} Keys(){ 90 | {{string.Concat(names.Select(static x=>$"yield return nameof({x});\n"))}} 91 | } 92 | """ 93 | )!) 94 | .AddMembers( 95 | $$""" 96 | public override {{CultureInfo}}? Culture 97 | { 98 | get => {{targetFullName}}.Culture; 99 | set 100 | { 101 | if (value == null) return; 102 | if (Equals({{targetFullName}}.Culture?.EnglishName, value.EnglishName)) return; 103 | {{targetFullName}}.Culture = value; 104 | UpdateSource(); 105 | OnChangeCompleted(); 106 | } 107 | } 108 | """, 109 | $$""" 110 | private void UpdateSource() 111 | { 112 | foreach(var key in this.Keys()){ 113 | OnPropertyChanged(key); 114 | } 115 | } 116 | """, 117 | $$""" 118 | [{{ModuleInitializer}}] 119 | public static void Initialize() 120 | { 121 | RegisterProvider(new {{className}}()); 122 | } 123 | """ 124 | ) 125 | .AddMembers(names.Select(x => 126 | $"public string {x} => {targetFullName}.{x};") 127 | .ToArray()) 128 | ) 129 | ) 130 | ).NormalizeWhitespace(); 131 | 132 | context.AddSource($"{generateCtx.TargetSymbol.GetFullyQualifiedName().Replace("global::", "")}.g.cs", 133 | unit.GetText(Encoding.UTF8)); 134 | 135 | } 136 | } 137 | } -------------------------------------------------------------------------------- /src/Antelcat.I18N.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.7.34202.233 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "__", "__", "{DAC60261-079A-44B4-8872-61FC02A4AE9F}" 7 | ProjectSection(SolutionItems) = preProject 8 | ..\Icon.png = ..\Icon.png 9 | ..\LICENSE = ..\LICENSE 10 | ..\README.en.md = ..\README.en.md 11 | ..\README.md = ..\README.md 12 | EndProjectSection 13 | EndProject 14 | Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Antelcat.I18N.Shared", "Antelcat.I18N.Shared\Antelcat.I18N.Shared.shproj", "{28F904C6-3B6D-4140-90FF-62A6BD87B0C6}" 15 | EndProject 16 | Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Antelcat.I18N.SourceGenerators.Shared", "Antelcat.I18N.SourceGenerators.Shared\Antelcat.I18N.SourceGenerators.Shared.shproj", "{15D71DC2-F53D-42EC-85E4-4982F6E351A5}" 17 | EndProject 18 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Shared", "Shared", "{F86CB7CC-4C0C-40AA-ABF0-282D7B15B38E}" 19 | EndProject 20 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Platforms", "Platforms", "{A9786647-4829-4617-98A5-704E2DDDCA35}" 21 | EndProject 22 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "WPF", "WPF", "{E03F942D-C1C1-4847-BA7D-5186A6CEAEE1}" 23 | EndProject 24 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Avalonia", "Avalonia", "{8122301E-0585-46DC-B4E5-3B6F12F8E237}" 25 | EndProject 26 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antelcat.I18N.SourceGenerators", "SourceGenerators\Antelcat.I18N.SourceGenerators.csproj", "{612D6836-4C01-48AA-A3BD-726ADDE0F101}" 27 | EndProject 28 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antelcat.I18N.WPF", "WPF\WPF\Antelcat.I18N.WPF.csproj", "{3C5623F8-1E58-456E-A386-11B7FBA42FA0}" 29 | EndProject 30 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antelcat.I18N.WPF.Demo", "WPF\Demo\Antelcat.I18N.WPF.Demo.csproj", "{7ECC81C2-D016-43C3-82F7-CCBEC9E30A15}" 31 | EndProject 32 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antelcat.I18N.WPF.Demo.Framework", "WPF\Demo.Framework\Antelcat.I18N.WPF.Demo.Framework.csproj", "{420430D4-4A39-4310-97B6-F9029575454B}" 33 | EndProject 34 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antelcat.I18N.Avalonia", "Avalonia\Avalonia\Antelcat.I18N.Avalonia.csproj", "{C0105DD2-CC54-47AB-9122-EEA1DC73E61E}" 35 | EndProject 36 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antelcat.I18N.Avalonia.Demo", "Avalonia\Demo\Antelcat.I18N.Avalonia.Demo.csproj", "{4BDD0948-3E41-4432-8EC2-395C3B694A3A}" 37 | EndProject 38 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antelcat.I18N.WPF.Library", "WPF\Library\Antelcat.I18N.WPF.Library.csproj", "{5FB0464B-DD43-4C4F-8F03-C0F8CEEB520E}" 39 | EndProject 40 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antelcat.I18N.Abstractions", "Antelcat.I18N.Abstractions\Antelcat.I18N.Abstractions.csproj", "{2BA15A8E-6C3E-4B33-BFF4-D9255202D71D}" 41 | EndProject 42 | Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Antelcat.I18N.Abstractions.Shared", "Antelcat.I18N.Abstractions.Shared\Antelcat.I18N.Abstractions.Shared.shproj", "{F3F24657-983C-46FF-B928-ADD03557C562}" 43 | EndProject 44 | Global 45 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 46 | Debug|Any CPU = Debug|Any CPU 47 | Release|Any CPU = Release|Any CPU 48 | EndGlobalSection 49 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 50 | {612D6836-4C01-48AA-A3BD-726ADDE0F101}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 51 | {612D6836-4C01-48AA-A3BD-726ADDE0F101}.Debug|Any CPU.Build.0 = Debug|Any CPU 52 | {612D6836-4C01-48AA-A3BD-726ADDE0F101}.Release|Any CPU.ActiveCfg = Release|Any CPU 53 | {612D6836-4C01-48AA-A3BD-726ADDE0F101}.Release|Any CPU.Build.0 = Release|Any CPU 54 | {3C5623F8-1E58-456E-A386-11B7FBA42FA0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 55 | {3C5623F8-1E58-456E-A386-11B7FBA42FA0}.Debug|Any CPU.Build.0 = Debug|Any CPU 56 | {3C5623F8-1E58-456E-A386-11B7FBA42FA0}.Release|Any CPU.ActiveCfg = Release|Any CPU 57 | {3C5623F8-1E58-456E-A386-11B7FBA42FA0}.Release|Any CPU.Build.0 = Release|Any CPU 58 | {7ECC81C2-D016-43C3-82F7-CCBEC9E30A15}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 59 | {7ECC81C2-D016-43C3-82F7-CCBEC9E30A15}.Debug|Any CPU.Build.0 = Debug|Any CPU 60 | {7ECC81C2-D016-43C3-82F7-CCBEC9E30A15}.Release|Any CPU.ActiveCfg = Release|Any CPU 61 | {7ECC81C2-D016-43C3-82F7-CCBEC9E30A15}.Release|Any CPU.Build.0 = Release|Any CPU 62 | {420430D4-4A39-4310-97B6-F9029575454B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 63 | {420430D4-4A39-4310-97B6-F9029575454B}.Debug|Any CPU.Build.0 = Debug|Any CPU 64 | {420430D4-4A39-4310-97B6-F9029575454B}.Release|Any CPU.ActiveCfg = Release|Any CPU 65 | {420430D4-4A39-4310-97B6-F9029575454B}.Release|Any CPU.Build.0 = Release|Any CPU 66 | {C0105DD2-CC54-47AB-9122-EEA1DC73E61E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 67 | {C0105DD2-CC54-47AB-9122-EEA1DC73E61E}.Debug|Any CPU.Build.0 = Debug|Any CPU 68 | {C0105DD2-CC54-47AB-9122-EEA1DC73E61E}.Release|Any CPU.ActiveCfg = Release|Any CPU 69 | {C0105DD2-CC54-47AB-9122-EEA1DC73E61E}.Release|Any CPU.Build.0 = Release|Any CPU 70 | {4BDD0948-3E41-4432-8EC2-395C3B694A3A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 71 | {4BDD0948-3E41-4432-8EC2-395C3B694A3A}.Debug|Any CPU.Build.0 = Debug|Any CPU 72 | {4BDD0948-3E41-4432-8EC2-395C3B694A3A}.Release|Any CPU.ActiveCfg = Release|Any CPU 73 | {4BDD0948-3E41-4432-8EC2-395C3B694A3A}.Release|Any CPU.Build.0 = Release|Any CPU 74 | {5FB0464B-DD43-4C4F-8F03-C0F8CEEB520E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 75 | {5FB0464B-DD43-4C4F-8F03-C0F8CEEB520E}.Debug|Any CPU.Build.0 = Debug|Any CPU 76 | {5FB0464B-DD43-4C4F-8F03-C0F8CEEB520E}.Release|Any CPU.ActiveCfg = Release|Any CPU 77 | {5FB0464B-DD43-4C4F-8F03-C0F8CEEB520E}.Release|Any CPU.Build.0 = Release|Any CPU 78 | {2BA15A8E-6C3E-4B33-BFF4-D9255202D71D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 79 | {2BA15A8E-6C3E-4B33-BFF4-D9255202D71D}.Debug|Any CPU.Build.0 = Debug|Any CPU 80 | {2BA15A8E-6C3E-4B33-BFF4-D9255202D71D}.Release|Any CPU.ActiveCfg = Release|Any CPU 81 | {2BA15A8E-6C3E-4B33-BFF4-D9255202D71D}.Release|Any CPU.Build.0 = Release|Any CPU 82 | EndGlobalSection 83 | GlobalSection(SolutionProperties) = preSolution 84 | HideSolutionNode = FALSE 85 | EndGlobalSection 86 | GlobalSection(NestedProjects) = preSolution 87 | {28F904C6-3B6D-4140-90FF-62A6BD87B0C6} = {F86CB7CC-4C0C-40AA-ABF0-282D7B15B38E} 88 | {15D71DC2-F53D-42EC-85E4-4982F6E351A5} = {F86CB7CC-4C0C-40AA-ABF0-282D7B15B38E} 89 | {E03F942D-C1C1-4847-BA7D-5186A6CEAEE1} = {A9786647-4829-4617-98A5-704E2DDDCA35} 90 | {8122301E-0585-46DC-B4E5-3B6F12F8E237} = {A9786647-4829-4617-98A5-704E2DDDCA35} 91 | {3C5623F8-1E58-456E-A386-11B7FBA42FA0} = {E03F942D-C1C1-4847-BA7D-5186A6CEAEE1} 92 | {7ECC81C2-D016-43C3-82F7-CCBEC9E30A15} = {E03F942D-C1C1-4847-BA7D-5186A6CEAEE1} 93 | {420430D4-4A39-4310-97B6-F9029575454B} = {E03F942D-C1C1-4847-BA7D-5186A6CEAEE1} 94 | {C0105DD2-CC54-47AB-9122-EEA1DC73E61E} = {8122301E-0585-46DC-B4E5-3B6F12F8E237} 95 | {4BDD0948-3E41-4432-8EC2-395C3B694A3A} = {8122301E-0585-46DC-B4E5-3B6F12F8E237} 96 | {5FB0464B-DD43-4C4F-8F03-C0F8CEEB520E} = {E03F942D-C1C1-4847-BA7D-5186A6CEAEE1} 97 | {F3F24657-983C-46FF-B928-ADD03557C562} = {F86CB7CC-4C0C-40AA-ABF0-282D7B15B38E} 98 | EndGlobalSection 99 | GlobalSection(ExtensibilityGlobals) = postSolution 100 | SolutionGuid = {73D6AEFA-1477-4119-9F85-0DA27E35BDB8} 101 | EndGlobalSection 102 | GlobalSection(SharedMSBuildProjectFiles) = preSolution 103 | Antelcat.I18N.SourceGenerators.Shared\Antelcat.I18N.SourceGenerators.Shared.projitems*{15d71dc2-f53d-42ec-85e4-4982f6e351a5}*SharedItemsImports = 13 104 | Antelcat.I18N.Shared\Antelcat.I18N.Shared.projitems*{28f904c6-3b6d-4140-90ff-62a6bd87b0c6}*SharedItemsImports = 13 105 | Antelcat.I18N.Abstractions.Shared\Antelcat.I18N.Abstractions.Shared.projitems*{2ba15a8e-6c3e-4b33-bff4-d9255202d71d}*SharedItemsImports = 5 106 | Antelcat.I18N.Shared\Antelcat.I18N.Shared.projitems*{3c5623f8-1e58-456e-a386-11b7fba42fa0}*SharedItemsImports = 5 107 | WPF\Shared.Demo\Antelcat.I18N.WPF.Demo.Shared.projitems*{5fb0464b-dd43-4c4f-8f03-c0f8ceeb520e}*SharedItemsImports = 5 108 | Antelcat.I18N.Abstractions.Shared\Antelcat.I18N.Abstractions.Shared.projitems*{612d6836-4c01-48aa-a3bd-726adde0f101}*SharedItemsImports = 5 109 | Antelcat.I18N.SourceGenerators.Shared\Antelcat.I18N.SourceGenerators.Shared.projitems*{612d6836-4c01-48aa-a3bd-726adde0f101}*SharedItemsImports = 5 110 | Antelcat.I18N.Shared\Antelcat.I18N.Shared.projitems*{c0105dd2-cc54-47ab-9122-eea1dc73e61e}*SharedItemsImports = 5 111 | Antelcat.I18N.Abstractions.Shared\Antelcat.I18N.Abstractions.Shared.projitems*{f3f24657-983c-46ff-b928-add03557c562}*SharedItemsImports = 13 112 | EndGlobalSection 113 | EndGlobal 114 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | .idea/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.tlog 95 | *.vspscc 96 | *.vssscc 97 | .builds 98 | *.pidb 99 | *.svclog 100 | *.scc 101 | 102 | # Chutzpah Test files 103 | _Chutzpah* 104 | 105 | # Visual C++ cache files 106 | ipch/ 107 | *.aps 108 | *.ncb 109 | *.opendb 110 | *.opensdf 111 | *.sdf 112 | *.cachefile 113 | *.VC.db 114 | *.VC.VC.opendb 115 | 116 | # Visual Studio profiler 117 | *.psess 118 | *.vsp 119 | *.vspx 120 | *.sap 121 | 122 | # Visual Studio Trace Files 123 | *.e2e 124 | 125 | # TFS 2012 Local Workspace 126 | $tf/ 127 | 128 | # Guidance Automation Toolkit 129 | *.gpState 130 | 131 | # ReSharper is a .NET coding add-in 132 | _ReSharper*/ 133 | *.[Rr]e[Ss]harper 134 | *.DotSettings.user 135 | 136 | # TeamCity is a build add-in 137 | _TeamCity* 138 | 139 | # DotCover is a Code Coverage Tool 140 | *.dotCover 141 | 142 | # AxoCover is a Code Coverage Tool 143 | .axoCover/* 144 | !.axoCover/settings.json 145 | 146 | # Coverlet is a free, cross platform Code Coverage Tool 147 | coverage*.json 148 | coverage*.xml 149 | coverage*.info 150 | 151 | # Visual Studio code coverage results 152 | *.coverage 153 | *.coveragexml 154 | 155 | # NCrunch 156 | _NCrunch_* 157 | .*crunch*.local.xml 158 | nCrunchTemp_* 159 | 160 | # MightyMoose 161 | *.mm.* 162 | AutoTest.Net/ 163 | 164 | # Web workbench (sass) 165 | .sass-cache/ 166 | 167 | # Installshield output folder 168 | [Ee]xpress/ 169 | 170 | # DocProject is a documentation generator add-in 171 | DocProject/buildhelp/ 172 | DocProject/Help/*.HxT 173 | DocProject/Help/*.HxC 174 | DocProject/Help/*.hhc 175 | DocProject/Help/*.hhk 176 | DocProject/Help/*.hhp 177 | DocProject/Help/Html2 178 | DocProject/Help/html 179 | 180 | # Click-Once directory 181 | publish/ 182 | 183 | # Publish Web Output 184 | *.[Pp]ublish.xml 185 | *.azurePubxml 186 | # Note: Comment the next line if you want to checkin your web deploy settings, 187 | # but database connection strings (with potential passwords) will be unencrypted 188 | *.pubxml 189 | *.publishproj 190 | 191 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 192 | # checkin your Azure Web App publish settings, but sensitive information contained 193 | # in these scripts will be unencrypted 194 | PublishScripts/ 195 | 196 | # NuGet Packages 197 | *.nupkg 198 | # NuGet Symbol Packages 199 | *.snupkg 200 | # The packages folder can be ignored because of Package Restore 201 | **/[Pp]ackages/* 202 | # except build/, which is used as an MSBuild target. 203 | !**/[Pp]ackages/build/ 204 | # Uncomment if necessary however generally it will be regenerated when needed 205 | #!**/[Pp]ackages/repositories.config 206 | # NuGet v3's project.json files produces more ignorable files 207 | *.nuget.props 208 | *.nuget.targets 209 | 210 | # Microsoft Azure Build Output 211 | csx/ 212 | *.build.csdef 213 | 214 | # Microsoft Azure Emulator 215 | ecf/ 216 | rcf/ 217 | 218 | # Windows Store app package directories and files 219 | AppPackages/ 220 | BundleArtifacts/ 221 | Package.StoreAssociation.xml 222 | _pkginfo.txt 223 | *.appx 224 | *.appxbundle 225 | *.appxupload 226 | 227 | # Visual Studio cache files 228 | # files ending in .cache can be ignored 229 | *.[Cc]ache 230 | # but keep track of directories ending in .cache 231 | !?*.[Cc]ache/ 232 | 233 | # Others 234 | ClientBin/ 235 | ~$* 236 | *~ 237 | *.dbmdl 238 | *.dbproj.schemaview 239 | *.jfm 240 | *.pfx 241 | *.publishsettings 242 | orleans.codegen.cs 243 | 244 | # Including strong name files can present a security risk 245 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 246 | #*.snk 247 | 248 | # Since there are multiple workflows, uncomment next line to ignore bower_components 249 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 250 | #bower_components/ 251 | 252 | # RIA/Silverlight projects 253 | Generated_Code/ 254 | 255 | # Backup & report files from converting an old project file 256 | # to a newer Visual Studio version. Backup files are not needed, 257 | # because we have git ;-) 258 | _UpgradeReport_Files/ 259 | Backup*/ 260 | UpgradeLog*.XML 261 | UpgradeLog*.htm 262 | ServiceFabricBackup/ 263 | *.rptproj.bak 264 | 265 | # SQL Server files 266 | *.mdf 267 | *.ldf 268 | *.ndf 269 | 270 | # Business Intelligence projects 271 | *.rdl.data 272 | *.bim.layout 273 | *.bim_*.settings 274 | *.rptproj.rsuser 275 | *- [Bb]ackup.rdl 276 | *- [Bb]ackup ([0-9]).rdl 277 | *- [Bb]ackup ([0-9][0-9]).rdl 278 | 279 | # Microsoft Fakes 280 | FakesAssemblies/ 281 | 282 | # GhostDoc plugin setting file 283 | *.GhostDoc.xml 284 | 285 | # Node.js Tools for Visual Studio 286 | .ntvs_analysis.dat 287 | node_modules/ 288 | 289 | # Visual Studio 6 build log 290 | *.plg 291 | 292 | # Visual Studio 6 workspace options file 293 | *.opt 294 | 295 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 296 | *.vbw 297 | 298 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 299 | *.vbp 300 | 301 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 302 | *.dsw 303 | *.dsp 304 | 305 | # Visual Studio 6 technical files 306 | *.ncb 307 | *.aps 308 | 309 | # Visual Studio LightSwitch build output 310 | **/*.HTMLClient/GeneratedArtifacts 311 | **/*.DesktopClient/GeneratedArtifacts 312 | **/*.DesktopClient/ModelManifest.xml 313 | **/*.Server/GeneratedArtifacts 314 | **/*.Server/ModelManifest.xml 315 | _Pvt_Extensions 316 | 317 | # Paket dependency manager 318 | .paket/paket.exe 319 | paket-files/ 320 | 321 | # FAKE - F# Make 322 | .fake/ 323 | 324 | # CodeRush personal settings 325 | .cr/personal 326 | 327 | # Python Tools for Visual Studio (PTVS) 328 | __pycache__/ 329 | *.pyc 330 | 331 | # Cake - Uncomment if you are using it 332 | # tools/** 333 | # !tools/packages.config 334 | 335 | # Tabs Studio 336 | *.tss 337 | 338 | # Telerik's JustMock configuration file 339 | *.jmconfig 340 | 341 | # BizTalk build output 342 | *.btp.cs 343 | *.btm.cs 344 | *.odx.cs 345 | *.xsd.cs 346 | 347 | # OpenCover UI analysis results 348 | OpenCover/ 349 | 350 | # Azure Stream Analytics local run output 351 | ASALocalRun/ 352 | 353 | # MSBuild Binary and Structured Log 354 | *.binlog 355 | 356 | # NVidia Nsight GPU debugger configuration file 357 | *.nvuser 358 | 359 | # MFractors (Xamarin productivity tool) working folder 360 | .mfractor/ 361 | 362 | # Local History for Visual Studio 363 | .localhistory/ 364 | 365 | # Visual Studio History (VSHistory) files 366 | .vshistory/ 367 | 368 | # BeatPulse healthcheck temp database 369 | healthchecksdb 370 | 371 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 372 | MigrationBackup/ 373 | 374 | # Ionide (cross platform F# VS Code tools) working folder 375 | .ionide/ 376 | 377 | # Fody - auto-generated XML schema 378 | FodyWeavers.xsd 379 | 380 | # VS Code files for those working on multiple tools 381 | .vscode/* 382 | !.vscode/settings.json 383 | !.vscode/tasks.json 384 | !.vscode/launch.json 385 | !.vscode/extensions.json 386 | *.code-workspace 387 | 388 | # Local History for Visual Studio Code 389 | .history/ 390 | 391 | # Windows Installer files from build outputs 392 | *.cab 393 | *.msi 394 | *.msix 395 | *.msm 396 | *.msp 397 | 398 | # JetBrains Rider 399 | *.sln.iml 400 | -------------------------------------------------------------------------------- /src/Antelcat.I18N.Shared/I18NExtension.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.ComponentModel; 3 | using System.Globalization; 4 | using System.Diagnostics; 5 | #if WPF 6 | using System.Windows.Data; 7 | using System.Windows.Markup; 8 | #elif AVALONIA 9 | using DependencyObject = Avalonia.AvaloniaObject; 10 | using Avalonia.Data; 11 | using Avalonia.Data.Converters; 12 | using Avalonia.Metadata; 13 | #endif 14 | 15 | using ResourceProvider = Antelcat.I18N.Abstractions.ResourceProvider; 16 | 17 | // ReSharper disable once CheckNamespace 18 | #if WPF 19 | namespace System.Windows; 20 | #elif AVALONIA 21 | namespace Avalonia.Markup.Xaml.MarkupExtensions; 22 | #endif 23 | 24 | [DebuggerDisplay("Key = {Key}, Keys = {Keys}")] 25 | public partial class I18NExtension : MarkupExtension, IAddChild 26 | { 27 | private static readonly IDictionary Target; 28 | private static readonly ResourceChangedNotifier Notifier; 29 | private static event CultureChangedHandler? CultureChanged; 30 | private static readonly Binding SourceBinding; 31 | 32 | private delegate void CultureChangedHandler(CultureInfo culture); 33 | 34 | /// 35 | /// Change the culture 36 | /// 37 | public static CultureInfo Culture 38 | { 39 | set => CultureChanged?.Invoke(value); 40 | } 41 | 42 | public static string? Translate(string key, string? fallbackValue = null) => 43 | Target.TryGetValue(key, out var value) 44 | ? value ?? fallbackValue 45 | : fallbackValue; 46 | 47 | private static partial void RegisterCultureChanged(ResourceProvider provider); 48 | 49 | private static void RegisterLanguageSource(ResourceProvider provider) 50 | { 51 | RegisterCultureChanged(provider); 52 | 53 | var keys = provider.Keys(); 54 | 55 | provider.PropertyChanged += (o, e) => Update(e.PropertyName); 56 | Notifier.RegisterProvider(provider); 57 | 58 | foreach (var key in keys) Update(key); 59 | 60 | void Update(string key) => Target[key] = provider[key]; 61 | } 62 | 63 | 64 | public I18NExtension(string key) : this() => Key = key; 65 | public I18NExtension(BindingBase binding) : this() => Key = binding; 66 | 67 | /// 68 | /// Resource key, accepts or . 69 | /// If Keys not null, Key will be the template of 70 | /// 71 | [DefaultValue(null)] 72 | public object? Key 73 | { 74 | get => proxy.GetValue(KeyProperty); 75 | set => proxy.SetValue(KeyProperty, value); 76 | } 77 | 78 | /// 79 | /// Same as . 80 | /// 81 | [DefaultValue(null)] 82 | public IValueConverter? Converter { get; set; } 83 | 84 | /// 85 | /// Same as . 86 | /// 87 | [DefaultValue(null)] 88 | public object? ConverterParameter { get; set; } 89 | 90 | private 91 | #if AVALONIA 92 | IBinding 93 | #elif WPF 94 | BindingBase 95 | #endif 96 | CreateBinding() => Key is string key && Keys.Count == 0 97 | ? CreateKeyBinding(key) 98 | : MapMultiBinding(); 99 | 100 | private Binding CreateKeyBinding(string key) => 101 | new(nameof(Notifier.Source)) 102 | { 103 | Source = Notifier, 104 | Mode = BindingMode.OneWay, 105 | FallbackValue = key, 106 | Converter = new StaticKeyConverter(key) 107 | { 108 | Converter = Converter, 109 | ConverterParameter = ConverterParameter 110 | }, 111 | #if WPF 112 | UpdateSourceTrigger = UpdateSourceTrigger.Explicit, 113 | #endif 114 | }; 115 | 116 | private MultiBinding MapMultiBinding() 117 | { 118 | var ret = CreateMultiBinding(); 119 | var isBindingList = new List(); 120 | List keys = []; 121 | List modes = []; 122 | switch (Key) 123 | { 124 | case string key: 125 | keys.Add(key); 126 | modes.Add(MultiValueLangConverter.Mode.Key); 127 | break; 128 | case Binding binding: 129 | ret.Bindings.Add(binding); 130 | modes.Add(MultiValueLangConverter.Mode.Binding); 131 | break; 132 | } 133 | 134 | foreach (var bindingBase in Keys) 135 | { 136 | switch (bindingBase) 137 | { 138 | case LanguageBinding languageBinding: 139 | if (languageBinding.Key is null) 140 | throw new ArgumentNullException($"Language key should be specified"); 141 | keys.Add(languageBinding.Key); 142 | modes.Add(MultiValueLangConverter.Mode.Key); 143 | break; 144 | case not null: 145 | ret.Bindings.Add(bindingBase); 146 | modes.Add(MultiValueLangConverter.Mode.Binding); 147 | break; 148 | default: 149 | throw new ArgumentException( 150 | $"{nameof(Keys)} only accept {typeof(LanguageBinding)} or {typeof(Binding)} current type is {bindingBase.GetType()}"); 151 | } 152 | 153 | isBindingList.Add(bindingBase is not LanguageBinding); 154 | } 155 | 156 | ret.Converter = new MultiValueLangConverter(isBindingList.ToArray(), modes.ToArray()) 157 | { 158 | Keys = keys.ToArray(), 159 | Converter = Converter, 160 | ConverterParameter = ConverterParameter, 161 | }; 162 | return ret; 163 | } 164 | 165 | private void CheckArgument() 166 | { 167 | if (Key is null && Keys.Count == 0) 168 | throw new ArgumentNullException($"{nameof(Key)} or {nameof(Keys)} cannot both be null"); 169 | if (Key is not null || Keys is not { Count: 1 }) return; 170 | Key = Keys[0]; 171 | Keys.Clear(); 172 | } 173 | 174 | public override partial object ProvideValue(IServiceProvider serviceProvider); 175 | 176 | public void AddChild(object value) 177 | { 178 | if (value is not Binding binding) return; 179 | Keys.Add(binding); 180 | } 181 | 182 | public void AddText(string key) 183 | { 184 | Keys.Add(new LanguageBinding(key)); 185 | } 186 | 187 | private class StaticKeyConverter(string key) : IValueConverter 188 | { 189 | public IValueConverter? Converter { get; set; } 190 | 191 | public object? ConverterParameter { get; set; } 192 | 193 | public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) => 194 | Converter?.Convert(Target[key], targetType, ConverterParameter, culture) ?? Target[key]; 195 | 196 | public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => 197 | throw new NotSupportedException(); 198 | } 199 | 200 | 201 | /// 202 | /// use to generate final text 203 | /// 204 | private class MultiValueLangConverter( 205 | #if !NET40 206 | IReadOnlyList 207 | #else 208 | IList 209 | #endif 210 | isBindingList, 211 | MultiValueLangConverter.Mode[] modes) : IMultiValueConverter 212 | { 213 | public enum Mode 214 | { 215 | Key, 216 | Binding, 217 | Plain 218 | } 219 | 220 | public string[] Keys { get; set; } = []; 221 | public IValueConverter? Converter { get; set; } 222 | public object? ConverterParameter { get; set; } 223 | 224 | private object[] GetValues(IList bindingValues, out string template) 225 | { 226 | template = string.Empty; 227 | var ret = new object[bindingValues.Count + Keys.Length - 1]; 228 | var index = 0; 229 | var keyIndex = 0; 230 | var bindingIndex = 1; // first is trigger 231 | foreach (var mode in modes) 232 | { 233 | string value = null!; 234 | switch (mode) 235 | { 236 | case Mode.Key: 237 | var key = Keys[keyIndex++]; 238 | value = Target.TryGetValue(key, out var k) ? k ?? key : key; 239 | break; 240 | case Mode.Binding: 241 | var binding = (bindingValues[bindingIndex++] as string)!; 242 | value = Target.TryGetValue(binding, out var t) ? t ?? binding : binding; 243 | break; 244 | } 245 | 246 | if (index == 0) template = value; 247 | else ret[index - 1] = value; 248 | index++; 249 | } 250 | 251 | return ret; 252 | } 253 | 254 | public object? Convert( 255 | #if WPF 256 | object?[] 257 | #elif AVALONIA 258 | IList 259 | #endif 260 | values, Type targetType, object? parameter, CultureInfo culture) 261 | { 262 | var vs = GetValues(values, out var tem); 263 | string v; 264 | try 265 | { 266 | v = string.Format(tem, vs); 267 | } 268 | catch 269 | { 270 | v = tem; 271 | } 272 | 273 | return Converter?.Convert(v, targetType, ConverterParameter, culture) ?? v; 274 | } 275 | 276 | public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) => 277 | throw new NotSupportedException(); 278 | } 279 | 280 | /// 281 | /// is singleton notifier for 282 | /// multibinding in case of avoid extra property notifier 283 | /// 284 | internal partial class ResourceChangedNotifier(INotifyPropertyChanged source) : INotifyPropertyChanged 285 | { 286 | public INotifyPropertyChanged Source => source; 287 | 288 | public event PropertyChangedEventHandler? PropertyChanged; 289 | 290 | private void OnPropertyChanged(string propertyName) => 291 | PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 292 | 293 | public void RegisterProvider(ResourceProvider provider) 294 | { 295 | if (this.provider is not null) this.provider.ChangeCompleted -= ChangeCompleted; 296 | this.provider = provider; 297 | provider.ChangeCompleted += ChangeCompleted; 298 | } 299 | 300 | private ResourceProvider? provider; 301 | 302 | private void ChangeCompleted(object sender, EventArgs eventArgs) 303 | { 304 | if (provider != sender) return; 305 | OnPropertyChanged(nameof(Source)); 306 | } 307 | } 308 | 309 | public class LanguageDictionary : IDictionary, INotifyPropertyChanged 310 | { 311 | private readonly Dictionary dict = []; 312 | public IEnumerator> GetEnumerator() => dict.GetEnumerator(); 313 | 314 | IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable)dict).GetEnumerator(); 315 | 316 | public void Add(KeyValuePair item) 317 | { 318 | dict.Add(item.Key, item.Value); 319 | OnPropertyChanged(item.Key); 320 | } 321 | 322 | public void Clear() => dict.Clear(); 323 | 324 | public bool Contains(KeyValuePair item) => dict.Contains(item); 325 | 326 | public void CopyTo(KeyValuePair[] array, int arrayIndex) 327 | { 328 | } 329 | 330 | public bool Remove(KeyValuePair item) 331 | { 332 | var value = dict.Remove(item.Key); 333 | OnPropertyChanged(item.Key); 334 | return value; 335 | } 336 | 337 | public int Count => dict.Count; 338 | 339 | public bool IsReadOnly => ((ICollection>)dict).IsReadOnly; 340 | 341 | public bool ContainsKey(string key) => dict.ContainsKey(key); 342 | 343 | public void Add(string key, string value) 344 | { 345 | dict.Add(key, value); 346 | OnPropertyChanged(key); 347 | } 348 | 349 | public bool Remove(string key) 350 | { 351 | var value = dict.Remove(key); 352 | OnPropertyChanged(key); 353 | return value; 354 | } 355 | 356 | public bool TryGetValue(string key, out string value) 357 | { 358 | if (key is null) 359 | { 360 | value = null; 361 | return false; 362 | } 363 | return dict.TryGetValue(key, out value); 364 | } 365 | 366 | public string this[string key] 367 | { 368 | get => dict.TryGetValue(key, out var value) ? value : key; 369 | set 370 | { 371 | dict[key] = value; 372 | OnPropertyChanged(key); 373 | } 374 | } 375 | 376 | public ICollection Keys => ((IDictionary)dict).Keys; 377 | 378 | public ICollection Values => ((IDictionary)dict).Values; 379 | public event PropertyChangedEventHandler? PropertyChanged; 380 | 381 | private void OnPropertyChanged(string propertyName) => 382 | PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 383 | } 384 | } --------------------------------------------------------------------------------