Skip to content

Instantly share code, notes, and snippets.

@louy
Created May 2, 2013 19:42
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 louy/5504829 to your computer and use it in GitHub Desktop.
Save louy/5504829 to your computer and use it in GitHub Desktop.
XAML C# GetElementsByTagName
/**
* By Louy Alakkad <me@l0uy.com>
*
* Copied from here: http://stackoverflow.com/questions/974598/find-all-controls-in-wpf-window-by-type
* With some modifications
*
* Javascript-like GetElementsByTagName function for XAML and C#
*
* You can use it like this:
* var elements = GetElementsByTagName<Image>(parent);
*/
public static IEnumerable<T> GetElementsByTagName<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment