简体   繁体   English

用资源更改WinForm的语言

[英]Change language of WinForm with resource

I have the following method that changes the language of the winform. 我有以下方法来更改winform的语言。

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

I call this method on the Form_Load method. 我在Form_Load方法上调用此方法。 Inside the form i have a tab control but the tabPage text property does not change. 在窗体内部我有一个选项卡控件但tabPage文本属性不会更改。 On the other hand the Label are changed correctly to the appropriate language. 另一方面, Label正确地更改为适当的语言。 Any suggestions? 有什么建议么?

Remove your method and try to do like this in Program.cs file: 删除您的方法并尝试在Program.cs文件中执行此操作:

//Add this line
Thread.CurrentThread.CurrentUICulture = new CultureInfo(languageString);
Application.Run(new Form());

Edit: 编辑:

The main thing why your code not working is that you applying language for form controls. 您的代码无效的主要原因是您为表单控件应用了语言。 This means that you applying to TabControl control, but TabControl also have controls(tab pages) "inside". 这意味着您应用于TabControl控件,但TabControl也有“内部”控件(标签页)。 So you need to iterate recursively through controls to apply language for all controls and sub controls. 因此,您需要通过控件递归迭代,以便为所有控件和子控件应用语言。 Try this code: 试试这段代码:

private void LoadLanguage(string lang)
{
    ComponentResourceManager resources = new ComponentResourceManager(typeof(main));
    CultureInfo cultureInfo = new CultureInfo(lang);

    doRecursiveLoading(this, cultureInfo, resources);
}

private void doRecursiveLoading(Control parent, CultureInfo cultureInfo,  ComponentResourceManager resources)
{
    foreach (Control c in parent.Controls)
    {
        resources.ApplyResources(c, c.Name, cultureInfo);
        if (c.Controls.Count > 0)
            doRecursiveLoading(c, cultureInfo, resources);
     }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM