C#从一个窗体本地化程序中打开的所有其他窗体



对我来说,标题中的问题似乎是一件普通的事情,人们可能会做或有问题,但我找不到任何关于这件事的信息。

我为正在构建的机器编写了一个小程序,希望将UI元素、警告消息等翻译成不同的语言。(德语和英语开头)。为此,我想在带有下拉组合框的"设置"窗体中设置语言。

我已经在这里找到了一个关于如何对表单进行一般本地化的工作示例,而VisualStudio并没有让它变得相当困难。从这里开始我该怎么做?我需要将一些变量传递给我打开的表单吗?或者我可以将语言设置为全局变量并在打开其他新表单时加载它。总共有6或7个表单在使用过程中会打开和关闭。

两种形式的示例代码:

namespace Test
{
public partial class MES : Form
{
public MES()
{
InitializeComponent();
}
private void Messen_Load(object sender, EventArgs e)
{
comboBox1.Items.Add("English");
comboBox1.Items.Add("Deutsch");
comboBox1.SelectedIndex = 0;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedItem.ToString() == "English")
{
ChangeLanguage("en");
}
else
{
ChangeLanguage("de-DE");
}
}
private void ChangeLanguage(string lang)
{
foreach (Control c in this.Controls)
{
ComponentResourceManager resources = new ComponentResourceManager(typeof(Messen));
resources.ApplyResources(c, c.Name, new CultureInfo(lang));
}
}
private void button2_Click(object sender, EventArgs e)
{
NewForm NF = new NewForm();
NF.Show();
this.Close();
}
}

更改MES表单中的标签和按钮名称确实有效,但NF表单中没有任何更改(本地化也设置为true,语言也相应设置)。

感谢您提前提供任何提示。

使用以下方法。源堆栈溢出您可以在localizedForm中将其作为引用传递。

private static void localizeForm(Form frm) {
var manager = new ComponentResourceManager(frm.GetType());
manager.ApplyResources(frm, "$this");
applyResources(manager, frm.Controls);
}
private static void applyResources(ComponentResourceManager manager, Control.ControlCollection ctls) {
foreach (Control ctl in ctls) {
manager.ApplyResources(ctl, ctl.Name);
applyResources(manager, ctl.Controls);
}
}

最新更新