代码改变世界

wpf与winForm界面控件遍历

2013-01-08 12:11  panmin  阅读(806)  评论(2)    收藏  举报

WinForm

    public void 遍历(Control c, ref  List<Control> list )
    {
       foreach (Control item in c.Controls)
        {
           list.Add(item);
           if (item.Controls != null && item.Controls.Count != 0)
           {
               遍历(item, ref list);
           }
        }  
    }
    public void GetAllControls()
    {
          List<Control> list = new List<Control>();
          遍历(this,ref list);
    }

wpf:

    public void 遍历(System.Collections.IEnumerable ie, ref List<UIElement> list)
    {
    foreach (object item in ie) {   if (item is UIElement) {    UIElement ui = item as UIElement;    list.Add(ui);   遍历(LogicalTreeHelper.GetChildren(ui), ref list); } }
}
public void GetAllControls() { List<UIElement> list = new List<UIElement>(); 遍历(LogicalTreeHelper.GetChildren(this) ,ref list); }

注:以上的代码中this都是指当前界面