Silverlight’s how to: get child elements
Silverlight’s how to: get child elements

Silverlight’s how to: get child elements

2010, Jan 12    

I’ve started studing Silverlight a while ago, I don’t think I’ll do something special or some amazing eye-candy application… I just want to see how it works.

Well….I don’t like it. I mean, it’s fantastic, allows you to do many wonderful things….but I do really hate all that xaml thing.  I still have to try some tools  like Expression Blend and Sketchflow , so I feel free to change my mind.

Anyway, during my code-nights I found this snippet on a forum, and I think it’s very useful for who (like me) prefer C#-coding over the xml-way-of-life. In a nutshell it’s an extension method  that allows you to recursively get a list of children of a specific type from an element. Here you go!

public static class Extensions
 {
        public static IEnumerable<T> GetChildren<T>(this FrameworkElement element) where T : FrameworkElement
        {
            int count = VisualTreeHelper.GetChildrenCount(element);
            for (int i = 0; i < count; i++)
            {
                var child = VisualTreeHelper.GetChild(element, i) as FrameworkElement;
                if (child is T) yield return (T)child;          
                var children = child.GetChildren<T>();
                foreach (T grandchild in children)  
                     yield return grandchild;
            }
        }
 }

Did you like this post? Then