使用silverlight4 Business构建企业级应用程序(一)——多语言支持

1. 资源的多语言支持

使用silverlight4生成默认的Silverlight Business Application后,出现Silverlight project ——MyApp and MyApp.Web.
· 在MyApp的Assets\Resources添加ApplicationStrings.zh-CN.resx,然后将ApplicationStrings.resx中的字符串拷贝到ApplicationStrings.zh-CN.resx中 改为中文资源说明;
· 编辑MyApp.csproj,添加多语言支持:en-US; zh-CN;
· 添加profile选项,支持用户选择语言:
首先在MyApp.Web的web.config中添加LanguagePreference 属性


<add name="LanguagePreference" type="string" defaultValue="auto" allowAnonymous="true"/>


然后在Models\User.cs中添加
///
/// Gets and sets the LanguagePreference name of the user.
///

public string LanguagePreference { get; set; }
在Models\RegistrationData.cs中添加
///
/// Gets and sets the LanguagePreference name of the user.
///

[Display(Order = 1, Name = "LanguagePreference", Description = "LanguagePreferenceDescription", ResourceType = typeof(RegistrationDataResources))]
public string LanguagePreference { get; set; }
在Service\UserRegisterationService.cs中的CreateUser函数中添加
profile.SetPropertyValue("LanguagePreference", user.LanguagePreference);
编译整个solution,silverlight端即可引用WebContext.Current.User.LanguagePreference。
打开Views\RegistrationForm.xaml,我们会看到现在的注册表单中最下面已经多了LanguagePreference这一项,文本框输入。但是最好的情况是ComboBox,我们在后台代码中的RegisterForm_AutoGeneratingField函数中的最后添加:
else if (e.PropertyName == "LanguagePreference")
{
ComboBox languageComboBox = new ComboBox();
languageComboBox.ItemsSource = LanguagePreferenceList;
e.Field.ReplaceTextBox(languageComboBox, ComboBox.SelectedItemProperty, binding => binding.Converter = new TargetNullValueConverter());
}
这里的LanguagePreferenceList枚举出语言类型:
public IEnumerable LanguagePreferenceList
{
get
{
// TODO: Resolve the available languages
yield return new CultureInfo("en-US");
yield return new CultureInfo("zh-CN");
yield return new CultureInfo("de");
}
}
为了在用户登录后调用相应的语言资源,在Views\Login\LoginStatus.xmal.cs中的UpdateLoginState()授权成功后的条件中添加:
string cultureTag = WebContext.Current.User.LanguagePreference;
if (!string.IsNullOrEmpty(cultureTag) && !cultureTag.Equals("auto"))
{
//UICulture - 决定了采用哪一种本地化资源,也就是使用哪种语言
//Culture - 决定各种数据类型是如何组织,如数字与日期
Thread.CurrentThread.CurrentUICulture = new CultureInfo(cultureTag);
Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureTag);
ApplicationStrings.Culture = new CultureInfo(cultureTag);
}
一般来说,至此就可以完成大部分情况下对多语言的支持。不过有些情况要求用户在程序运行时切换语言,然后所有打开的页面支持多语言的界面资源立即更新。这样我们就不得不采用另外的技术:参考文章http://www.wpftutorial.net/LocalizeMarkupExtension.html

Tags: 

延伸阅读

最新评论

发表评论