运行时本地化

Arm*_*yan 5 .net c# localization winforms

我用C#创建了Windows Form程序.本地化有一些问题.我有3种语言的资源文件.我想单击每个语言按钮并在运行时更改语言.当我在InitializeComponent()工作之前改变语言时.但是,当我点击按钮时,它不起作用.我正在使用此代码.

private void RussianFlag_Click(object sender, EventArgs e)
{
    Thread.CurrentThread.CurrentUICulture = new CultureInfo("ru-RU");
}
Run Code Online (Sandbox Code Playgroud)

小智 13

我写了一个RuntimeLocalizer包含以下功能的课程:

  • 更改和更新表单中所有Controls和SubControls的本地化
  • 也改变本地化所有SubItem所有第MenuStrip小号

用法示例: RuntimeLocalizer.ChangeCulture(MainForm, "en-US");


using System.Windows.Forms;
using System.Globalization;
using System.Threading;
using System.ComponentModel;
Run Code Online (Sandbox Code Playgroud)
public static class RuntimeLocalizer
{
    public static void ChangeCulture(Form frm, string cultureCode)
    {
        CultureInfo culture = CultureInfo.GetCultureInfo(cultureCode);

        Thread.CurrentThread.CurrentUICulture = culture;

        ComponentResourceManager resources = new ComponentResourceManager(frm.GetType());

        ApplyResourceToControl(resources, frm, culture);
        resources.ApplyResources(frm, "$this", culture);
    }

    private static void ApplyResourceToControl(ComponentResourceManager res, Control control, CultureInfo lang)
    {
        if (control.GetType() == typeof(MenuStrip))  // See if this is a menuStrip
        {
            MenuStrip strip = (MenuStrip)control;

            ApplyResourceToToolStripItemCollection(strip.Items, res, lang);
        }

        foreach (Control c in control.Controls) // Apply to all sub-controls
        {
            ApplyResourceToControl(res, c, lang);
            res.ApplyResources(c, c.Name, lang);
        }

        // Apply to self
        res.ApplyResources(control, control.Name, lang);
    }

    private static void ApplyResourceToToolStripItemCollection(ToolStripItemCollection col, ComponentResourceManager res, CultureInfo lang)
    {
        for (int i = 0; i < col.Count; i++)     // Apply to all sub items
        {
            ToolStripItem item = (ToolStripMenuItem)col[i];

            if (item.GetType() == typeof(ToolStripMenuItem))
            {
                ToolStripMenuItem menuitem = (ToolStripMenuItem)item;
                ApplyResourceToToolStripItemCollection(menuitem.DropDownItems, res, lang);
            }

            res.ApplyResources(item, item.Name, lang);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


V4V*_*tta 4

您将需要重新加载控件以反映新的文化价值观

ComponentResourceManager resources = new ComponentResourceManager(typeof(Form1));
Run Code Online (Sandbox Code Playgroud)

然后你必须使用每个控件来申请resources.ApplyResources

请看这里