Search code examples
wpfpopupdatepickervisual-tree

how do I loop through all controls on a popup


I'm trying to get the "PART_HeaderButton" from a DatePicker control and then apply a customized style. The problem is I can't search the visual tree to find this header button. The calendar is on a popup. It seems when the popup opens a new visual tree is created.

My question is how can I access the new generated visual tree and do my loop search?


Solution

  • private static IEnumerable<T> FindVisualChildren<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;
                }
            }
        }
    }
    

    This will return a list DependencyObjects of type that you passed as T from the object that you passed as parameter.