This commit is contained in:
wenyongda 2022-11-18 15:40:42 +08:00
parent 3617bcfaf0
commit ba9bd516a7

View File

@ -33,4 +33,114 @@ this.button.Text = "button1";
##### 1.2.1.1 click ##### 1.2.1.1 click
### 1.3 控件文本显示国际化
#### 1.3.1 使用资源文件方式
在解决方案根目录新建`App_GlobalResources`文件夹
新建 `Resource.en-US.resx` 资源文件
放置英文文本
新建 `Resource.resx`资源文件
放置默认简体中文文本
根目录新建 `ResourceCulture.cs`
```c#
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Resources;
using System.Text;
using System.Threading;
namespace WindowsFormsApp1
{
public class ResourceCulture
{
// 设置需要的语言文本资源文件
public static void SetCurrentCulture(string name)
{
if (string.IsNullOrEmpty(name))
{
name = "en-US";
}
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(name);
}
// 获取资源文件中的文本
public static string GetString(string id)
{
string strCurLanguage = "";
try
{
ResourceManager rm = new ResourceManager("WindowsFormsApp1.App_GlobalResources.Resource",
System.Reflection.Assembly.GetExecutingAssembly());
CultureInfo ci = Thread.CurrentThread.CurrentCulture;
strCurLanguage = rm.GetString(id, ci);
}
catch
{
strCurLanguage = "No id" + id + ", please add.";
}
return strCurLanguage;
}
}
}
```
控件里调用
新建initRes()方法
```c#
private void initRes()
{
// 设置 窗体form 名称
this.Text = ResourceCulture.GetString("Form1_frmText");
// 设置 分组框 groupbox 名称
this.gbLanguageView.Text = ResourceCulture.GetString("gbLanguageView_frmText");
this.gbLanguageSelection.Text = ResourceCulture.GetString("gbLanguageSelection_frmText");
}
```
可以在窗体初始化调用加载
```c#
private void Form1_Load(object sender, EventArgs e)
{
this.initRes();
}
```
如果是一个切换语言的窗体
新建可以切换的控件,这里使用`RadioButton`,因为是中英文切换,所以需要建两个`RadioButton`
使用`click`事件
```c#
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
ResourceCulture.SetCurrentCulture("en-US");
this.SetResourceCulture();
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
ResourceCulture.SetCurrentCulture("zh-CN");
this.SetResourceCulture();
}
```