通过反射获取Winform / UserControl中的所有复选框

本文关键字:复选框 UserControl 反射 获取 Winform | 更新日期: 2023-09-27 18:30:34

我想添加一个动态CheckAll()方法来检查我的类中声明的所有复选框。

我尝试了以下代码:

class MyContol : UserControl
{
  ///
  ///  HIDDEN but there is plenty of checkboxes declaration
  ///
  private void CheckAll()
  {
    FieldInfo[] props = this.GetType().GetFields();
    foreach (FieldInfo p in props)
    {
      if (p.FieldType is CheckBox)
      {
         /// TODO: Check my box
      }
    }
  }
}

。但props是空的。我不知道如何定位使用设计器零件制作的复选框。

您知道如何使用Reflection如何定位设计视图组件添加的目标吗?

通过反射获取Winform / UserControl中的所有复选框

控件的复选框应全部为子控件。也就是说,它们是Control.Controls集合中的子项(或可能是子项的子项)。此外,控件不必将它们作为类的属性或字段引用。例如,我可以使用 myControl.Controls.Add(new CheckBox()) 向现有控件添加一个复选框。因此,你不需要在这里反思,也不会真正得到你想要的——如果我理解正确的话。

尝试以这种方式枚举它们(要检查面板中的示例控件,您需要执行递归搜索):

private void CheckAll(Control parent)
{
    foreach(Control c in parent.Controls)
    {
        if (c is CheckBox)
            Check((CheckBox)c);
        CheckAll(c);
    }
}
private void CheckAll()
{
    CheckAll(this);
}
默认情况下,

UserControl 上的控件是私有字段,所以我想您应该提供非公共标志作为 GetFields 方法中绑定属性的参数,请尝试以下操作:

this.GetType().GetFields(System.Reflection.BindingFlags.NonPublic);

但是你不需要反思来实现你在这里寻找的东西。