如何在Windows Phone上更改C#中的本地化
本文关键字:本地化 Windows Phone | 更新日期: 2023-09-27 18:01:08
我有两种语言的资源文件,我的应用程序已经读取了其中一种语言的值。我希望能够在C#中更改我的应用程序的语言(使用其他资源文件(,而不是在"设置"中更改整个手机的语言。
这可能吗?如果是,如何?
在App.xaml.cs
中,在InitializePhoneApplication
方法中:
private void InitializePhoneApplication()
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
.......
}
限制是它需要在应用程序初始化中,因此如果用户更改语言,则需要重新启动才能生效。
您可以通过重新加载用户更改语言的页面并维护页面布局的RTL/LTR来完成此操作,而无需重新启动
我在App.xaml.cs 中添加了这个函数
public static void ChangeAppLanguage(string CultureName)
{
App.RootFrame.Language = XmlLanguage.GetLanguage(CultureName);
FlowDirection flow = (FlowDirection)Enum.Parse(typeof(FlowDirection), AppResources.ResourceFlowDirection);
App.RootFrame.FlowDirection = flow;
App.Current.RootVisual.UpdateLayout();
App.RootFrame.UpdateLayout();
var ReloadUri =( App.RootFrame.Content as PhoneApplicationPage).NavigationService.CurrentSource;
(Application.Current.RootVisual as PhoneApplicationFrame).Navigate(new Uri(ReloadUri + "?no-cache=" + Guid.NewGuid(), UriKind.Relative));
}
其中CultureName如下所示:"ar SA"、"en US">
我打电话给
private void EnglishMenuItem_Click(object sender, EventArgs e)
{
try
{
if(Thread.CurrentThread.CurrentCulture.Name == "en-US")
Thread.CurrentThread.CurrentCulture = new CultureInfo("ar-SA");
else
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
AppResources.Culture = Thread.CurrentThread.CurrentCulture;
App.ChangeAppLanguage(Thread.CurrentThread.CurrentCulture.Name);
//this._contentLoaded = false; //this way does not refresh appBar
//this.InitializeComponent();
//this way work for one time only => if user change language more thane once the api does NOT call constructor
//NavigationService.Navigate(new System.Uri("/PhoneApp2;component/MainPage.xaml", System.UriKind.Relative));
}
catch (Exception ex)
{
MessageBox.Show("error:'n'n" + ex.Message);
}
}