WPF

C# 다국어

Chanhongv 2024. 6. 20. 14:47
class TranslationSource : INotifyPropertyChanged
{
    private static readonly TranslationSource instance = new TranslationSource();
    public static TranslationSource Instance { get { return instance; } }

    private CultureInfo? currentCulture;
    public CultureInfo? CurrentCulture
    {
        get { return this.currentCulture; }
        set
        {
            if (this.currentCulture != value)
            {
                this.currentCulture = value;
                var @event = this.PropertyChanged;
                if (@event != null)
                {
                    @event.Invoke(this, new PropertyChangedEventArgs(string.Empty));
                }
            }
        }
    }

    public event PropertyChangedEventHandler? PropertyChanged;

    public string this[string key1, string key2]
    {
        get
        {
            if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                return $"[{key1},{key2}]";
            }

            var service = App.Current.Services.GetService(typeof(EFCoreService));
            if (service is EFCoreService eFCoreService)
            {
                string rtn = eFCoreService.Languages.GetString(key1, key2, CurrentCulture?.ThreeLetterISOLanguageName.ToUpper());
                return !string.IsNullOrWhiteSpace(rtn) ? rtn : $"[{key1},{key2}]"; ;
            }
            return $"[{key1},{key2}]";
        }
    }
}

 

인덱서에서 get 은 원하는데로 변경 가능하다.

 

    public class LocExtension : Binding
    {
        public LocExtension(string key1, string key2) : base($"[{key1},{key2}]")
        {
            this.Mode = BindingMode.OneWay;
            this.Source = TranslationSource.Instance;
        }
    }

 

사용법

<RadioButton Content="{lang:Loc SubMenuContent,ResultData}"/>​

 

위와 같이 사용 가능하다.