Finding ALL child controls WPF

后端 未结 2 1953
被撕碎了的回忆
被撕碎了的回忆 2020-12-01 18:33

I would like to find all of the controls within a WPF control. I have had a look at a lot of samples and it seems that they all either require a Name to be passed as paramet

2条回答
  •  無奈伤痛
    2020-12-01 19:17

    You can use these.

     public static List GetLogicalChildCollection(this DependencyObject parent) where T : DependencyObject
            {
                List logicalCollection = new List();
                GetLogicalChildCollection(parent, logicalCollection);
                return logicalCollection;
            }
    
     private static void GetLogicalChildCollection(DependencyObject parent, List logicalCollection) where T : DependencyObject
            {
                IEnumerable children = LogicalTreeHelper.GetChildren(parent);
                foreach (object child in children)
                {
                    if (child is DependencyObject)
                    {
                        DependencyObject depChild = child as DependencyObject;
                        if (child is T)
                        {
                            logicalCollection.Add(child as T);
                        }
                        GetLogicalChildCollection(depChild, logicalCollection);
                    }
                }
            }
    

    You can get child button controls in RootGrid f.e like that:

     List

提交回复
热议问题