56 lines
1.8 KiB
C#
56 lines
1.8 KiB
C#
using System.ComponentModel;
|
|
using System.Globalization;
|
|
using System.Reflection;
|
|
using System.Resources;
|
|
using System.Runtime.CompilerServices;
|
|
|
|
namespace JackCraft.I18N;
|
|
|
|
public sealed class I18NManager : INotifyPropertyChanged
|
|
{
|
|
public I18NManager(string baseName, Assembly? assembly = null)
|
|
{
|
|
I18NConfig.BaseName = baseName;
|
|
I18NConfig.Assembly = assembly ?? Assembly.GetCallingAssembly();
|
|
I18NConfig.Manager = this;
|
|
}
|
|
|
|
public CultureInfo Culture
|
|
{
|
|
get => I18NConfig.Culture;
|
|
set
|
|
{
|
|
if (Equals(value, I18NConfig.Culture)) return;
|
|
I18NConfig.Culture = value;
|
|
OnPropertyChanged();
|
|
}
|
|
}
|
|
|
|
public static string BaseName => I18NConfig.BaseName;
|
|
public static Assembly Assembly => I18NConfig.Assembly;
|
|
private ResourceManager ResourceManager => I18NConfig.ResourceManager;
|
|
public event PropertyChangedEventHandler? PropertyChanged;
|
|
|
|
private void OnPropertyChanged([CallerMemberName] string? propertyName = null)
|
|
{
|
|
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
|
|
}
|
|
|
|
public T? Get<T>(string key, CultureInfo? culture = null, params object?[] values)
|
|
{
|
|
culture ??= Culture;
|
|
var resourceSet = ResourceManager.GetResourceSet(culture, true, true);
|
|
var obj = resourceSet?.GetObject(key);
|
|
if (obj is string str && values.Length > 0) return (dynamic)string.Format(str, values);
|
|
if (obj != null) return (dynamic)obj;
|
|
return default;
|
|
}
|
|
|
|
public CultureInfo[] GetCultures()
|
|
{
|
|
var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures)
|
|
.Where(culture => ResourceManager.GetResourceSet(culture, true, false) != null)
|
|
.ToList();
|
|
return cultures.ToArray();
|
|
}
|
|
} |