ilverlight本地化
简单的实现多语言版本的Silverlight应用。
日益国际化的同时,需要我们开发的应用根据不同的来访者显示不用的语言,Silverlight在这个方面就提供了很方便的支持。
下来就来介绍一下如何做本地化
在VS中新建Silverlight项目
添加一个资源文件
添加一些文案,注意:Access Modifier 要设置为Public
然后复制这个文件,修改其名字做多语言支持。
相关列表请查阅这里:http://msdn.microsoft.com/zh-cn/vstudio/system.globalization.cultureinfo(VS.95).aspx
新建立一个值的转化类
?? ?public class ApplicationResources : IValueConverter ?? ?{ ?? ? ? ?private static readonly ResourceManager resourceManager = ?? ? ? ? ? ?new ResourceManager("slLocalization.MyStrings", ?? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Assembly.GetExecutingAssembly()); ?? ? ? ?private static CultureInfo uiCulture = Thread.CurrentThread.CurrentUICulture; ?? ? ? ?public static CultureInfo UiCulture ?? ? ? ?{ ?? ? ? ? ? ?get { return uiCulture; } ?? ? ? ? ? ?set { uiCulture = value; } ?? ? ? ?} ?? ? ? ?public string Get(string resource) ?? ? ? ?{ ?? ? ? ? ? ?return resourceManager.GetString(resource, UiCulture); ?? ? ? ?} ?? ? ? ?public object Convert(object value, Type targetType, object parameter, CultureInfo culture) ?? ? ? ?{ ?? ? ? ? ? ?var reader = (ApplicationResources)value; ?? ? ? ? ? ?return reader.Get((string)parameter); ?? ? ? ?} ?? ? ? ?public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) ?? ? ? ?{ ?? ? ? ? ? ?throw new NotImplementedException(); ?? ? ? ?} ?? ?}
修改App.xaml把ApplicationResources添加进去
<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" ?? ? ? ? ? ? xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"? ?? ? ? ? ? ? x:Class="slLocalization.App" ?? ? ? ? ? ? xmlns:sl="clr-namespace:slLocalization"? ?? ? ? ? ? ? > ?? ?<Application.Resources> ?? ? ? ?<sl:ApplicationResources ?x:Key="Localization"/> ?? ?</Application.Resources> </Application>
用Blend创建UI界面
将中间的文案做好数据绑定以及转换
?? <TextBlock? ?? ? ? ?HorizontalAlignment="Center"? ?? ? ? ?VerticalAlignment="Center"? ?? ? ? ?Text="{Binding ConverterParameter=Welcome,? ?? ? ? ? ? ? ? ? ? ? ? ?Converter={StaticResource Localization},? ?? ? ? ? ? ? ? ? ? ? ? ?Source={StaticResource Localization}}"? ?? ? ? ?TextWrapping="Wrap"/>
给RadioButton添加事件
?? ? ? ?private void RadioButton_Click(object sender, System.Windows.RoutedEventArgs e) ?? ? ? ?{ ?? ? ? ? ? ?RadioButton rb = sender as RadioButton; ?? ? ? ? ? ?ApplicationResources.UiCulture = new CultureInfo(rb.Content.ToString()); ?? ? ? ? ? ?Content.Children.Clear(); ?? ? ? ? ? ?Content.Children.Add(new txtWelcomeControl()); ?? ? ? ?}
下来到了关键的一步了?
编译应用程序 观察output窗口
发现我们的多语言资源文件并未打包到xap内
这里需要修改Silverlight的项目文件“*.csproj” 用记事本将其打开,找到“SupportedCultures”节点,把支持的语言加入进去。
?? ?<SupportedCultures> ?? ??? ?en,ja-JP,ko-KR,pl-PL,zh-CN ?? ?</SupportedCultures>
再进行编译
可以看到语言资源文件都打包到了xap内部。