Find a Childelement from DependancyObject

Posted by Abhi2434 under WPF category on | Views : 5293
I think everyone gets a requirement to find the chileElement in the control template that constitute the WPF DependancyObject. It is really not easy to find that using its name. You need to traverse the VisualChild to get it.

public static ChildItem FindVisualChild<childItem>(DependencyObject obj) where ChildItem : DependencyObject
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is ChildItem)
return (ChildItem)child;
ChildItem childOfChild = FindVisualChild<ChildItem>(child);
if (childOfChild != null)
return childOfChild;
return null;


Comments or Responses

Login to post response