Skip to content

Instantly share code, notes, and snippets.

@emoacht
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emoacht/7067f7d6b876aefde2eb to your computer and use it in GitHub Desktop.
Save emoacht/7067f7d6b876aefde2eb to your computer and use it in GitHub Desktop.
Get all descendent DependencyObjects of a DependencyObject.
public static class VisualTreeHelperAddition
{
public static IEnumerable<T> GetDescendents<T>(this DependencyObject parent) where T : DependencyObject
{
if (parent == null)
yield break;
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is T)
{
yield return (T)child;
}
// Return grandchild recursively.
foreach (T grandchild in GetDescendents<T>(child))
{
yield return grandchild;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment