2 つの言語のリソース ファイルがあり、アプリは既にそのうちの 1 つの値を読み取ります。[設定] で電話全体の言語を変更するのではなく、C# でアプリの言語を変更 (他のリソース ファイルを使用) できるようにしたいと考えています。
これは可能ですか?もしそうなら、どのように?
2 つの言語のリソース ファイルがあり、アプリは既にそのうちの 1 つの値を読み取ります。[設定] で電話全体の言語を変更するのではなく、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);
}
}