12

我有两种语言的资源文件,我的应用程序已经读取了其中一种语言的值。我希望能够在 C# 中更改我的应用程序的语言(使用其他资源文件),而不是在设置中更改整个手机的语言。

这可能吗?如果是这样,怎么做?

4

2 回答 2

9

App.xaml.cs,在InitializePhoneApplication方法中:

private void InitializePhoneApplication()
{
    Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
    Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
    .......
}

限制是它需要在应用程序初始化中,所以如果用户更改语言,则需要重新启动才能生效。

于 2013-02-26T16:28:57.400 回答
4

您可以通过重新加载用户更改语言的页面并维护页面布局的 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);
        }
    }
于 2013-06-16T08:18:00.680 回答