Recently I needed to traverse the visual tree of a Silverlight dependancy object (UI element) in order to find a child object with the type I was looking for.
As I didn’t know how far nested the child would be, I wrote a recursive helper function which will scan all child elements looking for the first instance it finds. I then extended this functionality with a overload allowing to specify the name of the object I was looking for. I thought it might be useful elsewhere, so here it is:
private T FindControlByType<T>(DependencyObject container) where T : DependencyObject { return FindControlByType<T>(container, null); } private T FindControlByType<T>(DependencyObject container, string name) where T : DependencyObject { T foundControl = null; //for each child object in the container for (int i = 0; i < VisualTreeHelper.GetChildrenCount(container); i++) { //is the object of the type we are looking for? if (VisualTreeHelper.GetChild(container, i) is T && (VisualTreeHelper.GetChild(container, i).GetValue(FrameworkElement.NameProperty).Equals(name) || name == null)) { foundControl = (T)VisualTreeHelper.GetChild(container, i); break; } //if not, does it have children? else if (VisualTreeHelper.GetChildrenCount(VisualTreeHelper.GetChild(container, i)) > 0) { //recursively look at its children foundControl = FindControlByType<T>(VisualTreeHelper.GetChild(container, i), name); if (foundControl != null) break; } } return foundControl; }
You can tweak the code to accept more parameters if you need more comparisons to match your object.
Recent Comments