C#|.NET|XAML : Get Children & Grandchildren

This is, again, an extension method (C#, .NET). This particular method is tested with Silverlight only, but I do not think there should be any problem in .NET 4.5 WPF. This is a useful method to get children of a given type inside a DependencyObject. For example, you want to get a list of all textblocks inside the grid of this form:

ChildrenList

You can get all TextBlocks inside LayoutRoot using following code:

IEnumerable<TextBlock> _textBlocks = LayoutRoot.GetChildrenByType<TextBlock>();

Here is the code of the extension method:

namespace YourCompanysAwesomeExtensionMethods
{
    public static class ViewExtensions
    {
        public static IEnumerable GetChildrenByType(this DependencyObject parent) where T : class
        {
            List _children = new List();
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)             {                 var child = VisualTreeHelper.GetChild(parent, i);                 if (child != null && child is T)                     _children.Add(child as T);                 if (VisualTreeHelper.GetChildrenCount(child) > 0)
                {
                    IEnumerable _subchildren = GetChildrenByType(child);
                    if (_subchildren.Count() > 0)
                    {
                        _children.AddRange(_subchildren);
                    }
                }
            }
            return _children as IEnumerable;
        }
    }
}
Advertisements

4 thoughts on “C#|.NET|XAML : Get Children & Grandchildren

  1. Pingback: Dew Drop – January 27, 2014 (#1710) | Morning Dew

  2. Pingback: Weekly Digest for Developers: Jan 19 – Jan 26, 2014 - Super Dev Resources

  3. Pingback: Windows App Developer Links – 2014-01-31 | Dan Rigby

  4. Pingback: C# | .NET Extension Methods | Sharp Statements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s