In the previous Windows Phone application globalization, we talked about how to create a Windows Phone application that supports multiple languages. In this article, let's make dig a little deeper. That is, you can set the current language on the setting interface. You do not need to re-enter the program to switch the current interface to the selected language. The premise is that Mango APIs are used. (So this article is only valid for project 7.1 ).
The example code in this article is based on Windows Phone application globalization. If you have not read this article, you can take a look.
So how can we switch the language without restarting the Application? On MSDN, we talked about the new language, which is only valid for newly created pages, that is, after the page executes the constructor, the switched language resources can be loaded. Since a new page is valid, you can switch the language to a new page. However, there is a problem: "What about the old pages and what about the pages in the navigation history ". Speaking of this, you should be able to think of the function of removing the previous page in the navigation history in mango API. What we need to do is to clear all the pages when the user switches the language and click back, and then navigate to the home page again. In this case, we also need to clear the previous setting interface. OK. Let's take a look at the specific code:
We need to rewrite the click-back event OnBackKeyPress
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e){ //set current language var lang = AppSettingHelper.GetValueOrDefault<string>("language", "en-US"); CultureInfo ci = new System.Globalization.CultureInfo(lang); AppResource.Culture = ci; Thread.CurrentThread.CurrentCulture = ci; Thread.CurrentThread.CurrentUICulture = ci; //remove all history pages while (NavigationService.CanGoBack) { NavigationService.RemoveBackEntry(); } NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative)); base.OnBackKeyPress(e);}
In this event, we need to do the following three things:
1. Set the current language
2. Remove the history page
3. Jump to the homepage
Next, we need to rewrite another event on the page to remove the current setting interface:
Protected override void OnNavigatedFrom (System. windows. navigation. navigationEventArgs e) {Deployment. current. dispatcher. beginInvoke (delegate {// remove current setting page NavigationService. removeBackEntry () ;}); base. onNavigatedFrom (e);} source code can be found here