Posts Tagged AllChildren

Silverlight AllChildren: find all of the visual children of a FrameworkElement


Our application has some occasions where we need to iterate the entire child tree of a visual component. Not a common thing in many applications, I use it to pass visual states to the sub elements of a tree, but if you need a routine for this purpose then I thought I would post mine here:  


        public static List<T> AllChildren<T>(this FrameworkElement ele, Func<DependencyObject, bool> whereFunc = null) where T : class
        {
            if (ele == null)
                return null;
            var output = new List<T>();
            var c = VisualTreeHelper.GetChildrenCount(ele);
            for (var i = 0; i < c; i++)
            {
                var ch = VisualTreeHelper.GetChild(ele, i);
                if (whereFunc != null)
                {
                    if (!whereFunc(ch))
                    {
                        continue;
                    }
                }
                if ((ch is T))
                    output.Add(ch as T);
                if (!(ch is FrameworkElement))
                    continue;

                output.AddRange((ch as FrameworkElement).AllChildren<T>(whereFunc));
            }
            return output;
        }

The function is an extension method that uses the generic Type to decide on the types of children to return.  It takes an optional “Where function” that can be used to stop iterating down branches of the visual tree – please note that the Where function doesn’t only get passed the Type components, it gets everything so you can stop the recursive operation when you want to.  If you don’t pass the Where parameter then all visual children are returned.  

 

                foreach (var c in panel.AllChildren<Control>((child) => !(child is FdTreeViewItem)))
                {
                    VisualStateManager.GoToState(c, "FlowSelected", true);
                } 

   

, , ,

5 Comments