如何递归地从控件集合的控件中找到控件?

时间:2018-11-13 13:52:46

标签: c# winforms

我的控件“ MyTextBox1 ”在container1控件下动态添加到form1上。这个form1可以是form2的子级,而form2可以是form3的子级,依此类推,如何从多控件集合中找到我的控件?

例如 MyTextBox1 存在于

  

form3.form2.form1.Container1.MyTextBox1

如何从多个控件集合中按名称查找控件?

我不想对每个控件集合使用递归。我正在寻找类似controls.Find()的智能/简短代码。

1 个答案:

答案 0 :(得分:1)

If you don't want to put it recoursive, you can try BFS (Breadth First Search); let's implement it as an extension method:

public static class ControlExtensions { 
  public static IEnumerable<Control> RecoursiveControls(this Control parent) {
    if (null == parent)
      throw new ArgumentNullException(nameof(parent));

    Queue<Control> agenda = new Queue<Control>(parent.Controls.OfType<Control>());

    while (agenda.Any()) {
      yield return agenda.Peek();

      foreach (var item in agenda.Dequeue().Controls.OfType<Control>())
        agenda.Enqueue(item);
    }
  }
}

Then you can use it as

// Let's find Button "MyButton1" somewhere on MyForm 
// (not necessary directly, but may be on some container)
Button myBytton = MyForm
  .RecoursiveControls()
  .OfType<Button>()
  .FirstOrDefault(btn => btn.Name == "MyButton1");