1

我想manipulate全部Controls在我form的使用中foreach loop,我目前正在使用以下方法:

 foreach (Control c in this.Controls)
 {
                ComponentResourceManager resourceManager = new ComponentResourceManager(typeof(Main));
                resourceManager.ApplyResources(c, c.Name, new CultureInfo(lang));
  }

这个问题是不包括其中foreach的控件。Containers

我如何才能将所有内容都包含Controls在内Containers

我想在 1 个或 2 个foreach循环中执行此操作。

4

2 回答 2

3

控件

将以下类添加到您的项目中:

public static class ControlExtensionMethods
{
    public static IEnumerable<Control> GetOffsprings(this Control @this)
    {
        foreach (Control child in @this.Controls)
        {
            yield return child;
            foreach (var offspring in GetOffsprings(child))
                yield return offspring;
        }
    }
}

它将返回调用者的所有子控件:

var offsprings = this.GetOffsprings();

您可以在循环中使用它:

foreach (Control c in this.GetOffsprings())
{
    // Do action
}

菜单项

将以下类添加到您的项目中:

public static class MenuStripExtensionMethods
{
    public static IEnumerable<ToolStripItem> GetSubItems(this ToolStrip @this)
    {
        foreach (ToolStripItem child in @this.Items)
        {
            yield return child;
            foreach (var offspring in child.GetSubItems())
                yield return offspring;
        }
    }

    public static IEnumerable<ToolStripItem> GetSubItems(this ToolStripItem @this)
    {
        if (!(@this is ToolStripDropDownItem))
            yield break;

        foreach (ToolStripItem child in ((ToolStripDropDownItem) @this).DropDownItems)
        {
            yield return child;
            foreach (var offspring in child.GetSubItems())
                yield return offspring;
        }
    }
}

它将返回调用者的所有子菜单项:

var allMenuItems = this.menuStrip1.GetSubItems()
于 2013-03-12T13:38:08.777 回答
2

使其递归:

private static void ApplyResources(ComponentResourceManager resourceManager,
                                   CultureInfo cultureInfo,
                                   Control container)
{
    foreach (var control in container.Controls)
    {
        resourceManager.ApplyResources(control, control.Name, cultureInfo);
        ApplyResources(resourceManager, cultureInfo, control);
    }
}

并像这样使用它:

var resourceManager = new ComponentResourceManager(typeof(Main));
var cultureInfo = new CultureInfo(lang);
ApplyResources(resourceManager, cultureInfo, this);
于 2013-03-12T13:27:47.537 回答