【问题标题】:Iteration over dynamically added nested controls迭代动态添加的嵌套控件
【发布时间】:2015-04-26 06:46:57
【问题描述】:

我在 WinForm 上有一个 GroupBox。另一个 GroupBox 在运行时添加到第一个 GroupBox 中。

在第二个 GroupBox 中添加了一些 PictureBox 控件。

现在我想迭代 PictureBoxes。

目前我的代码是:

foreach (Control gbFirst in this.Controls)
{
    GroupBox firstGroupBox = gbFirst as GroupBox; //First GroupBox
    if (firstGroupBox != null)
    {
        foreach (Control gbSecond in firstGroupBox.Controls)
        {
            GroupBox secondGroupBox = gbSecond as GroupBox; //Second groupBox
            if (secondGroupBox != null)
            {
                foreach (Control item in secondGroupBox.Controls)
                {
                    var pb = item as PictureBox; // PictureBox
                    if (pb != null)
                    {
                        string pbTag = pb.Tag.ToString();
                        string customTag = ipAddress + "OnOff";
                        if (pb.Tag.ToString() == ipAddress + "OnOff")
                        {
                            MethodInvoker action = delegate
                            {
                                pb.Image = Properties.Resources.MobiCheckerOnPng16;
                            };
                            pb.BeginInvoke(action);
                            break;
                        }
                    }
                }
            }

        }
    }
}

但是,与上述不同,我认为可能有一种简单或聪明的方法可以做到这一点。

是这样吗?

【问题讨论】:

  • 好吧,当然,如果您在运行时添加内部 GroupBox,那么您也将 PictureBoxes 添加到其中。为什么不在创建它们时将它们存储在List<PictureBox> 中,这样你就不必编写这种代码了?
  • 我为此在 github.com/dotnet/winforms 上创建了一个API Proposal: Add Descendants property for Control。如果你喜欢它,请点赞。

标签: c# winforms iteration controls


【解决方案1】:

用于任何级别的任何容器中的任何控件类型的通用函数:

public static List<T> FindControls<T>(Control container, bool dig) where T : Control
{
    List<T> retVal = new List<T>();
    foreach (Control item in container.Controls)
    {
        if (item is T)
            retVal.Add((T)item);
        if (dig && item.Controls.Count > 0)
            retVal.AddRange(FindControls<T>(item, dig));
    }
    return retVal;
}

dig 变量控制是否遍历子容器控件。例如,如果要查找从第一个 GroupBox (gbFirst) 开始的所有 PictureBox 控件,则必须调用

FindControls<PictureBox>(gbFirst, true);

如果将 dig 设置为 false,则只会枚举输入容器中的控件。

【讨论】:

  • @M.Mhdipour - 请您解释一下 dig 变量吗?
  • 已编辑以获取更多解释。
猜你喜欢
  • 2014-06-08
  • 2021-12-02
  • 2015-05-24
  • 1970-01-01
  • 2018-05-23
  • 1970-01-01
  • 1970-01-01
  • 2020-04-01
  • 1970-01-01
相关资源
最近更新 更多