48 lines
1.5 KiB
C#
48 lines
1.5 KiB
C#
using System.Globalization;
|
|
using System.Resources;
|
|
using System.Windows.Data;
|
|
using CommunityToolkit.Mvvm.ComponentModel;
|
|
|
|
namespace CursorLang.Services;
|
|
|
|
/// <summary>
|
|
/// Takes the strings from the resources and, when the language changes, asks WPF to
|
|
/// re-read every binding.
|
|
/// </summary>
|
|
public sealed class LocalizationService : ObservableObject, ILocalizationService
|
|
{
|
|
private static readonly ResourceManager Resources =
|
|
new("CursorLang.Resources.Strings", typeof(App).Assembly);
|
|
|
|
private CultureInfo _culture = CultureInfo.GetCultureInfo("en");
|
|
|
|
public string this[string key] => Resources.GetString(key, _culture) ?? key;
|
|
|
|
public IReadOnlyList<LanguageOption> AvailableLanguages { get; } =
|
|
[
|
|
new LanguageOption("en", "English"),
|
|
new LanguageOption("ru", "Русский"),
|
|
];
|
|
|
|
public string CurrentLanguage
|
|
{
|
|
get => _culture.TwoLetterISOLanguageName;
|
|
set
|
|
{
|
|
if (string.IsNullOrWhiteSpace(value) || value == CurrentLanguage)
|
|
{
|
|
return;
|
|
}
|
|
|
|
_culture = CultureInfo.GetCultureInfo(value);
|
|
CultureInfo.CurrentUICulture = _culture;
|
|
|
|
OnPropertyChanged(nameof(CurrentLanguage));
|
|
|
|
// We report a change of the indexer: that is how every binding of the
|
|
// {Binding Localization[Key]} kind updates, that is, all the interface text
|
|
OnPropertyChanged(Binding.IndexerName);
|
|
}
|
|
}
|
|
}
|