以Winform登录界面为示例:
首先建立一个中文的xml文件,一个英文的xml文件,一个App.config配置文件
English.xml核心代码
<?xml version="1.0" encoding="utf-8" ?>
<English>
<Login_UserName>UserName:</Login_UserName>
<Login_UserPwd>Password:</Login_UserPwd>
<Login_Login>Login</Login_Login>
</English>
Chinese.xml核心代码
<?xml version="1.0" encoding="utf-8" ?>
<Chinese>
<Login_UserName>用户名:</Login_UserName>
<Login_UserPwd>密码:</Login_UserPwd>
<Login_Login>登录</Login_Login>
</Chinese>
App.Config核心代码
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<!-- Language的值只能是Chinese(中文),English(英文) -->
<add key="Language" value="English"/>
</appSettings>
</configuration>
中英文切换核心代码实现
新建一个 GlobalData类
public class GlobalData
{
/// <summary>
/// 系统语言(Chinese(中文),English(英文)。。。)
/// </summary>
public static string SystemLanguage = System.Configuration.ConfigurationManager.AppSettings["Language"];
// 在调用ConfigurationManager时,要加载System.Configuration.dll
private static Language globalLanguage;
public static Language GlobalLanguage
{
get
{
if (globalLanguage == null)
{
globalLanguage = new Language();
return globalLanguage;
}
return globalLanguage;
}
}
}
再建立一个 Language 类,主要作用是初始化时加载xml语言配置文件
public class Language
{
#region 登陆界面
public string Login_UserName = "";
public string Login_UserPwd = "";
public string Login_Login = "";
#endregion
protected Dictionary<string, string> DicLanguage = new Dictionary<string, string>();
public Language()
{
XmlLoad(GlobalData.SystemLanguage);
BindLanguageText();
}
/// <summary>
/// 读取XML放到内存
/// </summary>
/// <param name="language"></param>
protected void XmlLoad(string language)
{
try
{
XmlDocument doc = new XmlDocument();
//这里要注意,程序的根目录下面要有一个Languages的文件夹,里面放的东西就是那两个
//语言配置文件
string address = AppDomain.CurrentDomain.BaseDirectory + "Languages\\" + language + ".xml";
doc.Load(address);
XmlElement root = doc.DocumentElement;
XmlNodeList nodeLst1 = root.ChildNodes;
foreach (XmlNode item in nodeLst1)
{
DicLanguage.Add(item.Name, item.InnerText);
}
}
catch (Exception ex)
{
throw ex;
}
}
public void BindLanguageText()
{
Login_UserName = DicLanguage["Login_UserName"];
Login_UserPwd = DicLanguage["Login_UserPwd"];
Login_Login = DicLanguage["Login_Login"];
}
}
初始化调用
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
SetLanguage(); //调用
}
private void SetLanguage()
{
this.lbUserName.Text = GlobalData.GlobalLanguage.Login_UserName;
this.lbPwd.Text = GlobalData.GlobalLanguage.Login_UserPwd;
this.btnLogin.Text = GlobalData.GlobalLanguage.Login_Login;
}
}
运行即可.
有一个不好的地方就是,每次切换完都要重启系统。