c# - 在 C# winform 中在运行时更改语言

标签 c# .net winforms

我想更改语言但是当我编译这个时弹出一个异常。它说

"Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "System.Type.resources" was correctly embedded or linked into assembly "mscorlib" at compile time, or that all the satellite assemblies required are loadable and fully signed."

 private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (comboBox1.SelectedItem.ToString() == "English")
        {
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("En");
            ChangeLanguage("En");
        }
        else if (comboBox1.SelectedItem.ToString() == "German")
        {
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("De");
            ChangeLanguage("De");
        }
    }


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

有什么建议吗?

最佳答案

 ComponentResourceManager resources = new ComponentResourceManager(typeof(Type));

构造函数的参数是错误的,您是在告诉它为 System.Type 寻找资源。这就是为什么它提示找不到“System.Type.resources”的原因。它永远找不到那些。

您需要传递您实际想要本地化的表单类型。请改用 this.GetType()。尽管这可能只会本地化您的选项表单,而不是应用程序中的其余窗口。您可以改为迭代 Application.OpenForms() 。还需要将本地化应用于所有 控件。不仅是表格上的那些,还有位于面板等容器内的那些。因此:

    private static void ChangeLanguage(string lang) {
        Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang);
        foreach (Form frm in Application.OpenForms) {
            localizeForm(frm);
        }
    }

    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);
        }
    }

小心使用像这样的 wiz-bang 功能。在使用您的程序时,实际上没有人会改变他们的母语。

关于c# - 在 C# winform 中在运行时更改语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21067507/

相关文章:

c# - HTML 选择项目在 asp.net 中计数

c# - Visual Studio : Make debugger aware that a function doesn't cause "side effects"

c# - 具有非依赖参数的构造函数注入(inject)

c# - linq查询并使用结果来设置属性

c# - 使用 C# 按 Alpha.Numeric 对 XML 节点进行排序

c# - C# 7.x 中的对象解构用例

c# - 是否存在 Application.Exit() 不引发 FormClosing 事件的情况?

c# - 如何在winforms中禁用表格面板的水平滚动条

c# - Winforms .Net 简单数据绑定(bind)不起作用

c# - 使用 JSON.net 获取 JToken 的名称/ key