近日在做一个sdk项目,因为要实现多语言切换,单独类库多语言这方面的实现不是很多,故整理如下。
假设我们默认语言是英文,添加这两个文件。两个资源文件中均添加 UserCenter_Title 字段,并给其赋值。注意访问修饰符设置成public。
如果是要实现多主题的话,可相应添加图片等资源。
继承INotifyPropertyChanged并实现,最终代码可能如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34class="csharp keyword">public class AdeasygoLocalizedStrings : INotifyPropertyChanged
    {
        private static AppResource _localizedResources = new AppResource();
 
        public AppResource AdeasygoLocalizedResource
        {
 
            get
            {
 
                return _localizedResources;
 
            }
 
            set
            {
 
                _localizedResources = value;
 
                NotifyPropertyChanged("AdeasygoLocalizedResource");
 
            }
 
        }
 
        public event PropertyChangedEventHandler PropertyChanged;
        public void NotifyPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
这一步非常重要,添加ResourceManager属性的Set方法,以支持语言的动态切换:
1 2 3 4 5 6 7 8 9 10 11 12 13 14/// <summary>
        ///   返回此类使用的缓存的 ResourceManager 实例。
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Adeasygo.Community.Sdk.Resources.AppResource", typeof(AppResource).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
            set { resourceMan = value; }
        }
public static void Init(string lang = "en")
        {
            ResourceManager resManager;
            switch (lang)
            {
                case "zh":
                    resManager = new ResourceManager("Sdk.Resources.AppResource-zh-CN", Assembly.Load("Sdk"));
                    break;
                default:
                    resManager = new ResourceManager("Sdk.Resources.AppResource", Assembly.Load("Sdk"));
                    break;
            }
            AppResource.ResourceManager = resManager;
        }
如此就实现了类库中动态的语言切换,图像资源等,也可以定义在resx中实现根据语言变化或者多主题切换。
本文固定链接: http://www.liubaicai.net/index.php/archives/425
欢迎访问:http://www.liubaicai.net/ 寻找更多