我几乎完成了我的 C# 应用程序;剩下要做的就是实现多语言支持。
我已经创建了资源文件,这些文件为屏幕上显示的所有文本保存了几种语言的字符串。
我的英语资源文件示例:
Name | Value | Comment
------------------------------------------------------------------------------
lblName | Name: | Name EN
我的荷兰资源文件示例:
Name | Value | Comment
------------------------------------------------------------------------------
lblName | Naam: | Name NL
如何将字段
Value
绑定(bind)到我的 Text
( Label
) 的 lblName
属性?我正在使用 .NET Framework 3.5。
最佳答案
我知道这个问题很久以前就有人问过,但由于没有答案,所以我建议:
要在 C# 中访问资源文件,您可以使用 ResourceManager 。
首先根据当前语言创建资源管理器。
为此,您有两种选择。您可以使用 switch 或 if 语句(如果语言由菜单决定)或使用本地化来使用计算机的当前区域性。最后,通过这两种方式,您都可以调用 GetString() 方法,提供我认为在您的情况下是 lblName 的 key 。
注意:在下面的示例中,我使用第一种方法,即从菜单中检索语言。
string selectedLanguage = comboBoxLang.Text; // Comes from a menu option
string resourceFile = string.Empty;
/***/
Logic to retrieve the proper resourceFile depending on the selectedLanguage.
/***/
ResourceManager rm = new ResourceManager(resourceFile, Assembly.GetExecutingAssembly());
// Set your label text.
lblName.Text = rm.GetString("lblName");