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

时间:2011-10-04 13:10:01

标签: c# windows forms globalization cultureinfo

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

我参加了这个教程: click

这适用于标签等,但它根本不适用于工具条菜单项。他们只保留默认文字。

我尝试在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.resources”正确嵌入或链接到程序集“System.Windows.Forms”中,或者所有所需的附属程序集都是可加载和完全签名的。

不确定如何继续 - 任何帮助表示感谢。

1 个答案:

答案 0 :(得分:2)

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

ToolstripMenuItems被添加到ToolStripItems DropDownItems集合中,而不是添加到Form的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);
    }
}