Reputation: 788
I have my Resource files with 2 languages and my app already reads the values of one of them. I would like to be able to change the language of my app (use the other resource file) in C# instead of changing the language of the whole phone in Settings.
Is this possible? If so, how?
Upvotes: 12
Views: 6895
Reputation: 1085
you can do this without need to restart by reloading the page where the user change a language and maintaining the RTL/LTR of your page layout
I added this function in 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));
}
where the CultureName like this : "ar-SA", "en-US"
and I called like this
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);
}
}
Upvotes: 4
Reputation: 15268
In App.xaml.cs
, in the InitializePhoneApplication
method:
private void InitializePhoneApplication()
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
.......
}
The limitation is that it needs to be in the app initialization, so if the user changes the language, a restart will be required for it to take effect.
Upvotes: 9