2010-02-05 16 views

回答

40

我使用扩展方法来扁平化控制层次结构,然后应用过滤器,以便使用自己的递归方法。

的方法是这样的

public static IEnumerable<Control> FlattenChildren(this Control control) 
{ 
    var children = control.Controls.Cast<Control>(); 
    return children.SelectMany(c => FlattenChildren(c)).Concat(children); 
} 
+1

您能否提供一个代码示例? – abatishchev 2010-02-05 19:44:04

+1

当然,添加了代码 – 2010-02-05 19:55:34

+1

真的很好的一段代码,感谢分享! – 2011-09-15 14:25:05

1

地改善上述的答案会是有意义的返回类型更改为

//Returns all controls of a certain type in all levels: 
public static IEnumerable<TheControlType> AllControls<TheControlType>(this Control theStartControl) where TheControlType : Control 
{ 
    var controlsInThisLevel = theStartControl.Controls.Cast<Control>(); 
    return controlsInThisLevel.SelectMany(AllControls<TheControlType>).Concat(controlsInThisLevel.OfType<TheControlType>()); 
} 

//(Another way) Returns all controls of a certain type in all levels, integrity derivation: 
public static IEnumerable<TheControlType> AllControlsOfType<TheControlType>(this Control theStartControl) where TheControlType : Control 
{ 
    return theStartControl.AllControls().OfType<TheControlType>(); 
} 
1

我用这个通用的递归方法:

假设这种方法是,如果控件是T而不是方法不看它的子项。如果你还需要看看它的孩子,你可以很容易地相应地改变它。

public static IList<T> GetAllControlsRecusrvive<T>(Control control) where T :Control 
{ 
    var rtn = new List<T>(); 
    foreach (Control item in control.Controls) 
    { 
     var ctr = item as T; 
     if (ctr!=null) 
     { 
      rtn.Add(ctr); 
     } 
     else 
     { 
      rtn.AddRange(GetAllControlsRecusrvive<T>(item)); 
     } 

    } 
    return rtn; 
} 
相关问题