C# WPF 国际化

一、静态字段

  1. 同级目录下添加Languages文件夹,所需的国际化翻译放在该文件夹下,国际化翻译文件类似:zh-cn.xaml
  2. 修改App.xaml
<ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="Languages/zh-cn.xaml"></ResourceDictionary>
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
  1. 添加“LanguageSelection()”函数,最好放在“Application_Startup”函数最前面。
private void LanguageSelection()
{
    //获取当前UI国籍
    string localregion = CultureInfo.CurrentUICulture.Name.ToLower();
    //枚举当前的资源文件并删除
    var appResource = App.Current.Resources.MergedDictionaries;
    List<int> dellist = new List<int>();
    dellist.Clear();
    int icount = 0;
    foreach (ResourceDictionary item in appResource)
    {
        if (item.Source.ToString().Contains("Languages/"))
        {
            dellist.Add(icount);
        }
        icount++;
    }
    foreach (int i in dellist)
    {
        appResource.RemoveAt(i);
    }
    //添加当前语言选项
    ResourceDictionary resdic = new ResourceDictionary();
    string LanguageDesc = "zh-cn";
    if (!localregion.Equals("zh-cn"))
    {
        LanguageDesc = "en";
    }
    //for new
    string strurl = String.Format("../Languages/{0}.xaml", LanguageDesc);
    //string strurl = String.Format("../Languages/{0}.xaml", "en");
    resdic.Source = new Uri(strurl, UriKind.Relative);
    try
    {
        appResource.Insert(0, resdic);
    }
    catch
    {
        resdic.Source = new Uri("../Languages/zh-cn.xaml", UriKind.Relative);
        appResource.Insert(0, resdic);
    }
}

二、动态字段

  1. 同级目录下添加“Languages”文件夹,所需的国际化翻译放在该文件夹下,国际化翻译文件类似:“zh-cn.xaml”
  2. 修改“App.xaml”
<ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="Languages/zh-cn.xaml"></ResourceDictionary>
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
注:使用字段需要使用“DynamicResource”,例:<TextBlock Text="{DynamicResource title}"/>
  1. 添加“LanguageSelection()”函数,切换按钮的函数。
public bool flag = true;
private void Button_Click(object sender, RoutedEventArgs e)
{
    string strurl;
    if (flag)
    {
        strurl = String.Format("zh-cn.xaml");
    }
    else
    {
        strurl = String.Format("en-us.xaml");
    }
    var rd = new ResourceDictionary() { Source = new Uri(strurl, UriKind.RelativeOrAbsolute) };
    if (Application.Current.Resources.MergedDictionaries.Count == 0)
    {
        Application.Current.Resources.MergedDictionaries.Add(rd);
    }
    else
    {
        Application.Current.Resources.MergedDictionaries[0] = rd;
    }
     flag = !flag;
}

类似文章