Created
May 2, 2013 19:42
-
-
Save louy/5504829 to your computer and use it in GitHub Desktop.
XAML C# GetElementsByTagName
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* By Louy Alakkad <[email protected]> | |
* | |
* 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