How to find out the elements of particular type in my WPF UserControl ?

Aug 14, 2009 at 7:40 PM

I have a WPF UserControl. I want to find out all the elements of a particular type( Button or DataGrid) inside my user control. I want to do this on the lost focus of UserControl. How do i do this ?

 

Regards,

Bhupesh.

Aug 15, 2009 at 3:03 AM

Hi Bhupesh,

Do you want this?

public static void GetAllChildObjectOfTypeInVisualTree<T>(DependencyObject dpob, List<T> outList) where T : DependencyObject
{
        int count = VisualTreeHelper.GetChildrenCount(dpob);
        for (int i = 0; i < count; i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(dpob, i);
            T childAsT = child as T;
            if (childAsT != null)
            {
                outList.Add(childAsT);
            }
            GetAllChildObjectOfTypeInVisualTree<T>(child, outList);
        }           
}

 

Best Regards,

Tony