背水一戰 Windows 10 (80) - 本地化


[源碼下載]


背水一戰 Windows 10 (80) - 本地化



作者:webabcd


介紹
背水一戰 Windows 10 之 本地化

  • Demo
  • 改變語言



示例
1、演示本地化的基本應用
Localization/LocalizationDemo.xaml

<Page
    x:Class="Windows10.Localization.LocalizationDemo"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Windows10.Localization"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="Transparent">
        <Grid.Resources>
            <ResourceDictionary>
                <local:LocalizedStrings x:Key="Localized"/>
            </ResourceDictionary>
        </Grid.Resources>

        <StackPanel Margin="10 0 10 10">

            <TextBlock>
                <Run>本地化資源文件,以下舉例說明:</Run>
                <LineBreak />
                <Run>1、在 en 目錄下的是英文資源文件,在 zh-hans 目錄下的是簡體中文(zh 代表中文,hans 代表簡體中文)資源文件(關於限定符的詳細說明請參見 /Resource/Qualifiers/)</Run>
                <LineBreak />
                <Run>2、Resources.lang-en.resw 代表英文資源文件,Resources.lang-zh-hans.resw 代表簡體中文資源文件(關於限定符的詳細說明請參見 /Resource/Qualifiers/)</Run>
                <LineBreak />
                <Run>3、Package.appxmanifest 中引用的字符串也支持本地化,引用方式:ms-resource:Hello 或 ms-resource:///Resources/Hello</Run>
                <LineBreak />
                <Run>4、Tile 和 Toast 中引用的字符串也支持本地化,引用方式:ms-resource:Hello 或 ms-resource:///Resources/Hello</Run>
                <LineBreak />
                <Run>5、當無法找到某語言對應的資源時,系統會自動使用 Package.appxmanifest 中設置的默認語言所對應的資源</Run>
            </TextBlock>

            <!--
                通過 x:Uid 本地化控件的各個屬性,請參看資源文件中的 HelloTextBlock.FontSize 和 HelloTextBlock.Text
            -->
            <TextBlock x:Uid="HelloTextBlock" Margin="5" />

            <!--
                圖片的本地化
            -->
            <Image Source="/Localization/Logo.png" Width="200" Height="100" Margin="5" HorizontalAlignment="Left" />

            <!--
                code - behind 方式獲取本地化資源
            -->
            <TextBlock x:Name="lblMsg1" Margin="5" />

            <!--
                code - behind 方式獲取本地化資源
            -->
            <TextBlock x:Name="lblMsg2" Margin="5" />

            <!--
                code - behind 方式獲取本地化資源
            -->
            <TextBlock x:Name="lblMsg3" Margin="5" />

            <!--
                code - behind 方式獲取本地化資源
            -->
            <TextBlock x:Name="lblMsg4" Margin="5" />

            <!--
                code - behind 方式獲取本地化資源
            -->
            <TextBlock x:Name="lblMsg5" Margin="5" />

            <!--
                綁定本地化資源
            -->
            <TextBlock x:Name="lblMsg6" Margin="5" Text="{Binding [Hello], Source={StaticResource Localized}}" />

        </StackPanel>
    </Grid>
</Page>

Localization/LocalizationDemo.xaml.cs

/*
 * 演示本地化的基本應用
 * 
 * 
 * 注:建議使用多語言應用工具包 https://developer.microsoft.com/zh-cn/windows/develop/multilingual-app-toolkit
 */

using System;
using System.Resources;
using Windows.ApplicationModel.Resources;
using Windows.ApplicationModel.Resources.Core;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace Windows10.Localization
{
    public sealed partial class LocalizationDemo : Page
    {
        public LocalizationDemo()
        {
            this.InitializeComponent(); 
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            /*
             * ResourceLoader resourceLoader = ResourceLoader.GetForViewIndependentUse(); - 獲取默認的 ResourceLoader(Resources.resw 中的資源)
             * ResourceLoader resourceLoader = ResourceLoader.GetForViewIndependentUse("MyResources"); - 獲取指定的 ResourceLoader(MyResources.resw 中的資源)
             * ResourceLoader resourceLoader = ResourceLoader.GetForViewIndependentUse("ClassLibrary/MyResources"); - 獲取指定類庫的指定的 ResourceLoader(ClassLibrary 類庫中的 MyResources.resw 中的資源)
             * resourceLoader.GetString(), resourceLoader.GetStringForUri() - 通過資源標識,獲取當前語言環境的指定的資源
             * 
             * GetForCurrentView() 和 GetForViewIndependentUse() 的區別如下:
             * 1、GetForCurrentView() - 在 UI 線程上執行
             * 2、GetForViewIndependentUse() - 在非 UI 線程上執行(注:Independent 這個詞在 uwp 中就時非 UI 線程的意思,比如 Independent Animation 就是不依賴 UI 線程的)
             */

            // 獲取默認的 ResourceLoader(即 Resources.resw 中的資源)
            ResourceLoader resourceLoader = ResourceLoader.GetForViewIndependentUse();

            // 通過資源標識,獲取當前語言環境的指定的資源(資源名:Hello)
            lblMsg1.Text = resourceLoader.GetString("Hello");

            // 通過資源標識,獲取當前語言環境的指定的資源(資源名:HelloTextBlock.Text)
            lblMsg2.Text = resourceLoader.GetString("HelloTextBlock/Text");

            // 通過資源標識,獲取當前語言環境的指定的資源(資源名:Hello)
            lblMsg3.Text = resourceLoader.GetStringForUri(new Uri("ms-resource:///Resources/Hello"));

            // 通過資源標識,獲取當前語言環境的指定的資源(資源名:HelloTextBlock.Text)
            lblMsg4.Text = resourceLoader.GetStringForUri(new Uri("ms-resource:///Resources/HelloTextBlock/Text"));

            // 獲取當前語言環境的指定的資源的另一種方式
            lblMsg5.Text = Windows.ApplicationModel.Resources.Core.ResourceManager.Current.MainResourceMap.GetValue("Resources/Hello", ResourceContext.GetForCurrentView()).ValueAsString;
        }
    }

    // 用於演示如何綁定本地化資源
    public class LocalizedStrings
    {
        public string this[string key]
        {
            get
            {
                return ResourceLoader.GetForCurrentView().GetString(key);
            }
        }
    }
}


2、演示與“改變語言”相關的一些應用
Localization/Language.xaml

<Page
    x:Class="Windows10.Localization.Language"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Windows10.Localization"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="Transparent">
        <StackPanel Name="root" Margin="10 0 10 10">

            <!--
                通過此種方式獲取本地化資源時,如果在頁面加載后修改了語言首選項的話是不會立即有效果的,需要重新加載頁面才行(懶的寫了,要看效果的話就先返回,然后再進來就好)
            -->
            <TextBlock x:Uid="HelloTextBlock" Margin="5" />

            <ComboBox Name="cmbLanguage" Width="800" HorizontalAlignment="Left" Margin="5" />

            <Button Name="btnGetEnglish" Content="獲取英文資源" Margin="5" Click="btnGetEnglish_Click" />
            <Button Name="btnGetChinese" Content="獲取簡體中文資源" Margin="5" Click="btnGetChinese_Click" />

            <TextBlock Name="lblMsg" Margin="5" />

        </StackPanel>
    </Grid>
</Page>

Localization/Language.xaml.cs

/*
 * 演示與“改變語言”相關的一些應用
 * 
 * 1、演示如何改變當前的語言環境
 * 2、演示如何監測當前語言環境發生的變化
 * 3、演示如何獲取指定語言環境下的資源
 */

using System;
using System.Collections.Generic;
using System.Text;
using Windows.ApplicationModel.Resources;
using Windows.ApplicationModel.Resources.Core;
using Windows.Globalization;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Windows10.Localization
{
    public sealed partial class Language : Page
    {
        public Language()
        {
            this.InitializeComponent();

            this.Loaded += Language_Loaded;
        }

        void Language_Loaded(object sender, RoutedEventArgs e)
        {
            // 獲取當前的語言
            string currentLanguage;
            ResourceContext.GetForCurrentView().QualifierValues.TryGetValue("Language", out currentLanguage);
            lblMsg.Text = "current language: " + currentLanguage;
            lblMsg.Text += Environment.NewLine;


            // ApplicationLanguages.ManifestLanguages - 遍歷 Package.appxmanifest 中的語言列表
            foreach (string strLang in ApplicationLanguages.ManifestLanguages)
            {
                // 關於 Language 的說明詳見 GlobalizationDemo.xaml
                var lang = new Windows.Globalization.Language(strLang);
                cmbLanguage.Items.Add(string.Format("DisplayName:{0}, NativeName:{1}, LanguageTag:{2}, Script:{3}",
                    lang.DisplayName, lang.NativeName, lang.LanguageTag, lang.Script));
            }
            cmbLanguage.SelectionChanged += cmbLanguage_SelectionChanged;


            // 獲取當前語言環境的指定資源(更多用法請參見 LocalizationDemo.xaml)
            lblMsg.Text += ResourceLoader.GetForViewIndependentUse().GetString("Hello");


            // 當前語言環境發生改變時所觸發的事件(通過 API 更改或者通過“電腦設置 -> 常規 -> 語言首選項”更改都會觸發此事件)
            // 注:當通過 API(ApplicationLanguages.PrimaryLanguageOverride)修改語言環境時,如果監聽了 MapChanged 事件的話,則有很大的幾率會導致崩潰,本例就是這樣,原因未知
            ResourceContext.GetForCurrentView().QualifierValues.MapChanged += async (s, m) =>
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    lblMsg.Text += Environment.NewLine;
                    lblMsg.Text += ResourceLoader.GetForViewIndependentUse().GetString("Hello");
                });
            };
        }

        private void cmbLanguage_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // ApplicationLanguages.PrimaryLanguageOverride - 設置或獲取首選語言(BCP-47 語言標記)
            if (cmbLanguage.SelectedValue.ToString().ToLower().Contains("en-us"))
                ApplicationLanguages.PrimaryLanguageOverride = "en-US";
            else if (cmbLanguage.SelectedValue.ToString().ToLower().Contains("zh-hans"))
                ApplicationLanguages.PrimaryLanguageOverride = "zh-Hans-CN";

            StringBuilder sb = new StringBuilder();
            // ApplicationLanguages.Languages - 按語言級別排序,獲取語言列表
            foreach (string item in ApplicationLanguages.Languages)
            {
                sb.Append(item);
                sb.Append(",");
            }

            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "ApplicationLanguages.Languages: " + sb.ToString();
        }

        private void btnGetEnglish_Click(object sender, RoutedEventArgs e)
        {
            // 指定 ResourceContext 為 en-US 語言環境
            ResourceContext resourceContext = new ResourceContext();
            resourceContext.Languages = new List<string>() { "en-US" };

            // 獲取 en-US 語言環境下的 Resources 映射
            ResourceMap resourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources");
            lblMsg.Text += Environment.NewLine;
            // 獲取指定的語言環境下的指定標識的資源
            lblMsg.Text += "英語的 Hello: " + resourceMap.GetValue("Hello", resourceContext).ValueAsString;
        }

        private void btnGetChinese_Click(object sender, RoutedEventArgs e)
        {
            // 指定 ResourceContext 為 zh-Hans-CN 語言環境
            ResourceContext resourceContext = new ResourceContext();
            resourceContext.Languages = new List<string>() { "zh-Hans-CN" };

            // 獲取 zh-Hans 語言環境下的 Resources 映射
            ResourceMap resourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources");
            lblMsg.Text += Environment.NewLine;
            // 獲取指定的語言環境下的指定標識的資源
            lblMsg.Text += "簡體中文的 Hello: " + resourceMap.GetValue("Hello", resourceContext).ValueAsString;
        }
    }
}



OK
[源碼下載]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM