Silverlight本地化
簡單的實作多語言版本的Silverlight應用。
日益國際化的同時,需要我們開發的應用根據不同的來訪者顯示不用的語言,Silverlight在這個方面就提供了很友善的支援。
下來就來介紹一下如何做本地化
在VS中建立Silverlight項目
添加一個資源檔案
添加一些文案,注意:Access Modifier 要設定為Public
然後複制這個檔案,修改其名字做多語言支援。
建立立一個值的轉化類
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内部。
測試運作:
源檔案下載下傳: