WPF多语言功能简单示例

一.本功能的原理

1为不同语言创建不同的资源文件,如en-us.xamlzh-cn.xaml

2、在App.xaml加载时根据配置文件的值读取不同的资源文件

3、在各窗体的xaml文件中利用动态绑定显示资源文件内容

4、更改不同语言需修改配置文件的值并重新启动程序,也可获取当前操作系统的语言类型在启动时读取不同的语言资源文件

 

en-us.xaml(zh-cn.xaml将内容改为中文) 

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    

                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    

                    xmlns:s="clr-namespace:System;assembly=mscorlib">

    <s:String x:Key="MainWindowTitle">Localization Demos</s:String>

    <s:String x:Key="LanguageMenuHeader">_Languages</s:String>

    <s:String x:Key="EnglishMenuHeader">_Englishs</s:String>

    <s:String x:Key="ChineseMenuHeader">_EnglishsHeader</s:String>

    <s:String x:Key="OpenLanguageFileMenuHeader">_Open Language Files</s:String>

</ResourceDictionary>

 

 创建配置文件并读取(需引入System.configuration)

  <appSettings>

    <add key="Lang" value="/Resources/Langs/en-us.xaml" />

  </appSettings>

 

public partial class App : Application

    {

        protected override void OnStartup(StartupEventArgs e)

        {

            base.OnStartup(e);

            string langType = ConfigurationManager.AppSettings.Get("Lang");

            App.Current.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri(langType, UriKind.RelativeOrAbsolute) });

        }

}

动态绑定:

    <StackPanel VirtualizingStackPanel.VirtualizationMode="Recycling" HorizontalAlignment="Left" VerticalAlignment="Top">

        <Label Content="{DynamicResource MainWindowTitle}"/>

        <Label Content="{DynamicResource LanguageMenuHeader}"/>

        <Label Content="{DynamicResource EnglishMenuHeader}"/>

        <Label Content="{DynamicResource ChineseMenuHeader}"/>

        <Label Content="{DynamicResource OpenLanguageFileMenuHeader}"/>

    </StackPanel>

修改配置文件值:

  XmlDocument doc = new XmlDocument();

            doc.Load(path);

            XmlNode node = doc.SelectSingleNode(@"//add[@key='Lang']");

            XmlElement ele = (XmlElement)node;

            ele.SetAttribute("value", Type);

            doc.Save(path);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值