WP8里dll类库(SDK)实现多语言多主题

Posted by baicai on February 5, 2015

近日在做一个sdk项目,因为要实现多语言切换,单独类库多语言这方面的实现不是很多,故整理如下。</span> </p>

1.添加AppResource.resx(英文)和AppResource-zh-CN.resx 

假设我们默认语言是英文,添加这两个文件。两个资源文件中均添加&nbsp;UserCenter_Title 字段,并给其赋值。注意访问修饰符设置成public。</span> </p>

如果是要实现多主题的话,可相应添加图片等资源。</span> </p>

20150205180508

2.添加LocalizedStrings类</span> </h2>

继承INotifyPropertyChanged并实现,最终代码可能如下</span> </p>

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));
            }
        }
    }

3.修改AppResource.Designer.cs

这一步非常重要,添加ResourceManager属性的Set方法,以支持语言的动态切换:

/// <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; }
        }

4.控制语言(主题)切换

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中实现根据语言变化或者多主题切换。</span> </p>