首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

Silverlight 4 多語言實作完整指南:資源檔、繫結與動態切換

     編輯:ASP.NET 基礎

建立多語言資源檔

  1. 在專案中新增資料夾 Resource,加入資源檔 AppString.resx(預設語言)。
  2. 複製一份並重新命名為對應文化特性名稱,例如 AppString.en-US.resx(英文)、AppString.zh-CN.resx(簡體中文)。
  3. 將 AppString.resx 的存取修飾詞設為 Public,並確認其對應的 .cs 檔案中類別修飾詞也為 public。

資源檔建立示意

在 App.xaml 註冊資源

開啟 App.xaml,加入資源參考,供其他頁面繫結使用:

App.xaml 資源註冊

頁面繫結資源字串

在 XAML 頁面中即可透過 {Binding Source={StaticResource AppStrings}, Path=KeyName} 方式繫結顯示多語言文字:

頁面繫結示例

語言切換核心類別:Configure

利用 IsolatedStorageSettings 儲存使用者選擇的語言,實現跨工作階段記憶:

public class Configure
{
    static System.Globalization.CultureInfo currentCulture;

    public static System.Globalization.CultureInfo CurrentCulture
    {
        get
        {
            if (currentCulture == null)
            {
                try
                {
                    var appSetting = System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings;
                    if (appSetting.Contains("language"))
                        currentCulture = new System.Globalization.CultureInfo((string)appSetting["language"]);
                }
                catch { }
            }
            if (currentCulture == null)
                currentCulture = new System.Globalization.CultureInfo("en-us");
            return currentCulture;
        }
        set
        {
            currentCulture = value;
            System.Threading.Thread.CurrentThread.CurrentCulture = currentCulture;
            System.Threading.Thread.CurrentThread.CurrentUICulture = currentCulture;
            try
            {
                var appSetting = System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings;
                if (appSetting.Contains("language"))
                {
                    appSetting["language"] = currentCulture.Name;
                    appSetting.Save();
                }
                else
                    appSetting.Add("language", currentCulture.Name);
            }
            catch { }
        }
    }
}

切換按鈕事件處理

private void button3_Click(object sender, RoutedEventArgs e)
{
    Configure.CurrentCulture = new CultureInfo(comboBox1.SelectionBoxItem.ToString());
}

應用程式啟動時套用語言

在 App.xaml.cs 的 Application_Startup 中讀取儲存的語言設定:

private void Application_Startup(object sender, StartupEventArgs e)
{
    CultureInfo culture = Configure.CurrentCulture;
    Thread.CurrentThread.CurrentUICulture = culture;
    Thread.CurrentThread.CurrentCulture = culture;
    this.RootVisual = new MainPage();
}

注意事項

切換語言後需重新啟動應用程式才能生效,並非即時切換。運行效果如下:

多語言切換效果圖

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved