切换语言(cultureinfo/globalization)不会影响ToolStripMenuItems

本文关键字:影响 ToolStripMenuItems globalization 语言 cultureinfo | 更新日期: 2023-09-27 18:10:19

我有一个Windows窗体应用程序项目,在主窗体上我有一个菜单条。在这个菜单栏的某些地方,可以选择各种语言。例如,如果用户选择"English",则此主表单(以及将来的其他表单)上的所有内容都应转换为英语。

我选择了这个教程:点击

这可以很好地处理标签等,但它根本不能处理工具条菜单项。它们只是保持默认文本。

我试图在ChangeLanguage方法中再添加两行:

private void ChangeLanguage(string lang)
{
    foreach (Control c in this.Controls)
    {
        ComponentResourceManager resources = new ComponentResourceManager(typeof(Form1));
        resources.ApplyResources(c, c.Name, new CultureInfo(lang));
        ComponentResourceManager res2 = new ComponentResourceManager(typeof(ToolStripMenuItem));
        res2.ApplyResources(c, c.Name, new CultureInfo(lang));
    }
}

但是它失败了,说:

找不到适合指定区域性或中性区域性的任何资源。确保"System.Windows.Forms.ToolStripMenuItem"。资源被正确地嵌入或链接到汇编程序中。

不知道如何继续-任何帮助感谢。

切换语言(cultureinfo/globalization)不会影响ToolStripMenuItems

您必须删除foreach循环中的最后两行。这几行表明您正在System.Windows.Forms.ToolStripMenuItem.resx文件中查找本地化信息,但是您想要查看窗体资源文件。

ToolstripMenuItems被添加到ToolStripItems DropDownItems集合中,而不是添加到窗体的Controls集合中。这可能有助于你解决问题。

private void ChangeLanguage(string lang) {
    ComponentResourceManager resources = new ComponentResourceManager(typeof(Form1));
    foreach (Control c in this.Controls) {
        resources.ApplyResources(c, c.Name, new CultureInfo(lang));
    }
    foreach (ToolStripItem item in toolStrip1.Items) {
        if (item is ToolStripDropDownItem)
            foreach (ToolStripItem dropDownItem in ((ToolStripDropDownItem)item).DropDownItems) {
                resources.ApplyResources(dropDownItem, dropDownItem.Name, new CultureInfo(lang));
            }
    }
}

如果你有更多的下拉项,你应该考虑递归的方法。

编辑:对我的第一个评论

private void ChangeLanguage(string lang) {
    ComponentResourceManager resources = new ComponentResourceManager(typeof(Form1));
    foreach (Control c in this.Controls) {
        resources.ApplyResources(c, c.Name, new CultureInfo(lang));
    }

ChangeLanguage (toolStrip1.Items);}

private void ChangeLanguage(ToolStripItemCollection collection) {
    foreach (ToolStripItem item in collection) {
        resources.ApplyResources(item, item.Name, new CultureInfo(lang));
        if (item is ToolStripDropDownItem)
            ChangeLanguage(((ToolStripDropDownItem)item).DropDownItems);
    }
}