【问题标题】:How to get all Buttons (or any other type) from Panel?如何从面板中获取所有按钮(或任何其他类型)?
【发布时间】:2015-08-10 22:25:54
【问题描述】:

我想从任何 ControlCollection 中获取所有相应类型的控件。重要的是要知道,我将一些元数据存储在控件的 Tag 属性中。 下面是我取回对应T类型控件的方法:

public static void GetAllChildControls<T>(Control.ControlCollection root, List<T> list) where T : Control {
  if (list == null)
    list = new List<T>();
  foreach (Control ctl in root) {
    if (ctl.GetType() == typeof(T))
      list.Add((T)ctl);
    if (ctl.Controls.Count > 0)
      GetAllChildControls(ctl.Controls, list);
  }
}

我写这篇文章的唯一原因是因为我没有取回 Tag 的值。在 VS2008 中 (T)ctl 没有可评估的标签(和 ContextMenu 也是如此)。它显示“无法评估表达式”。否则所有其他事情似乎都可以。

更新

我询问 Tag 属性的代码:

...
List<Button> list = null;
Helper.GetAllChildControls<Button>(master.ChildControls, list);
if (list != null)
  foreach (CounterItem c in counters) {
    Button b = list.Single(e => e.Tag.Equals(c.Name));
                                  ^^^
    if (b == null)
      continue;
    b.SetCounter(c.Value);
  }
...

【问题讨论】:

  • 贴出你使用 Tag 属性的代码
  • @E-Bat 完成,帖子已更新
  • 您遇到的行为/错误是什么?
  • 是编译异常?运行?。顺便说一句,请注意 if (b == null) 行永远不会被评估为 Single linq 方法如果找不到匹配项会引发异常,也许您需要更改为 SingleOrDefault
  • 我通过评估 e.Tag 得到运行时错误“无法评估表达式”。顺便说一句 b == null 真的没有意义......

标签: winforms .net-3.5 compact-framework


【解决方案1】:

你调用方法的方式永远不会产生任何结果:

List<Button> list = null;
Helper.GetAllChildControls<Button>(master.ChildControls, list);
....
public static void GetAllChildControls<T>(Control.ControlCollection root, List<T> list) where T : Control 
{
    if (list == null)
        list = new List<T>();

由于您没有将参数作为ref List&lt;T&gt; list 传递,因此将创建方法范围内的list,但调用者范围内的list 仍然会null

如果我是你,我会让 GetAllChildControls&lt;T&gt; 返回一个列表:

public static List<T> GetAllChildControls<T>(Control.ControlCollection root) where ...

【讨论】:

  • 不认为你希望它返回 List
  • 我已经在实时代码中的列表之前添加了 ref 但没关系,标签仍然是“无法评估表达式”...
  • @cdkMoose,在这个片段中没有机会成为Combobox,按钮类型在他的泛型方法中被过滤掉
  • @E-Bat,第二个代码sn-p为真,但第一个代码sn-p中的定义被泛化为Type T,所以不适合将结果定义为List
猜你喜欢
  • 1970-01-01
  • 2020-02-11
  • 2014-04-25
  • 1970-01-01
  • 2012-02-11
  • 1970-01-01
  • 2017-09-15
  • 2011-09-27
  • 2012-04-04
相关资源
最近更新 更多