Thursday, April 29, 2010

WPF: Find All Child Controls Of A Type

The following DependencyObject extension method (compatible with both WPF and Silverlight) recursively traverses the visual tree searching for children of the type specified by type parameter TChild before returning a collection containing the matches.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media;


namespace WPFFindAllChildren
{
public static class DependencyObjectExtension
{
public static List<TChild> FindChildren<TChild>(this DependencyObject d)
where TChild : DependencyObject
{
List<TChild> children = new List<TChild>();

int childCount = VisualTreeHelper.GetChildrenCount(d);

for (int i = 0; i < childCount; i++)
{
DependencyObject o = VisualTreeHelper.GetChild(d, i);

if (o is TChild)
children.Add(o as TChild);

foreach (TChild c in o.FindChildren<TChild>())
children.Add(c);
}

return children;
}
}
}


Usage

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace WPFFindAllChildren
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}

void Window1_Loaded(object sender, RoutedEventArgs e)
{
StackPanel stack1 = new StackPanel();
stack1.Children.Add(new CheckBox());
stack1.Children.Add(new CheckBox());

StackPanel stack2 = new StackPanel();
stack2.Children.Add(new CheckBox());
stack2.Children.Add(stack1);

LayoutRoot.Children.Add(stack2);

this.FindChildren<CheckBox>().ForEach(x => x.IsChecked = true);
}
}
}



Download Sample