我想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
中包含所有foreach
?
我想在1个或2个{{1}}循环中执行此操作。
答案 0 :(得分: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()
答案 1 :(得分: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);