Often we need to loop through the controls (collection of TextBlocks in) to and find them by their types. We can find them in this way:-
object control= LayoutRoot.FindName(txtname.Text);
if (item is TextBox)
TextBox txtControl = (TextBox)item;
txtControl.Text = "Yup! Got you!";
Put his code for any given control and you can find it,where we're supplying the name of the textbox through txtname.Text.
Great idea,isn't it?
But if you need to find it by type and I tell you that I am having approximately 100 controls over a very complex control panel designed in wpf and you need to find a list of child controls,then?
Getting all of them using names is a repetitive and bad idea. So we can use the VisualTreeHelper class which gets the children as nodes.
The getchild method of this class the children as Dependency Objects which is the base object of all WPF objects
So we can use following method to get children in a WPF window:-
public static IEnumerable<T> FindWindowChildren<T>(DependencyObject dObj) where T : DependencyObject
if (dObj!= null)
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dObj); i++)
DependencyObject ch = VisualTreeHelper.GetChild(dObj, i);
if (ch != null && ch is T)
yield return (T)ch;
foreach (T nestedChild in FindWindowChildren<T>(ch))
yield return nestedChild;
now call the method in your constructor(after initializeComponent method) and use it like following:-
foreach (TextBlock tblk in FindWindowChildren<TextBlock>(window))
// use tblk here for something creative
If you are finding that your method is returning 0 children,try running the method in Loaded event of window rather than in constructor.
If you want invisible elements to be included,just use LogicalTreeHelper in place of VisualTreeHelper in the method.
So you can create a helper class with this method and use it wherever you want.