1. Dotnet9首页
  2. .NET
  3. WPF

WPF的一种动态切语言方法

使用 resx 文件,可以动态切换语言,

新建Lang.zh-CN.resx  Lang.en-US.resx 资源文件

新建空类Lang.cs

新建如下类:

public class LanguageManager : INotifyPropertyChanged
    {
        private readonly ResourceManager _resourceManager;
        private static readonly Lazy<LanguageManager> _lazy = new Lazy<LanguageManager>(() => new LanguageManager());      
        public static LanguageManager Instance => _lazy.Value;
        public event PropertyChangedEventHandler PropertyChanged;

        private LanguageManager()
        {
            _resourceManager = new ResourceManager(typeof(Lang));
        }

        public string this[string name]
        {
            get
            {
                if (name == null)
                {
                    throw new ArgumentNullException(nameof(name));
                }
                return _resourceManager.GetString(name);
            }
        }

        public void ChangeLanguage(CultureInfo cultureInfo)
        {
            CultureInfo.CurrentCulture = cultureInfo;
            CultureInfo.CurrentUICulture = cultureInfo;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Item[]"));
        }
    }

使用方法:

<TextBlock FontSize="20" Margin="10" Text="{Binding [String1], Source={x:Static local:LanguageManager.Instance}}"/>

切换语言:

LanguageManager.Instance.ChangeLanguage(new CultureInfo("zh-CN"));
WPF的一种动态切语言方法

源码已上传至Gitgub

除非注明,文章均由 Dotnet9 整理发布,欢迎转载。

转载请注明本文地址:https://dotnet9.com/10145.html

发表评论

登录后才能评论