Search code examples
c#wpfvisual-tree

Visual Tree - Find a label (anywhere on the window) where content equals


I have many labels as children of many different stack panels which are all children of a list box, and I need to reference one of these labels were the Content.toString() == "criteria". In other words, traversing the visual tree in WPF would be a ball ache because there are many parent/child methods to run. Is there a way of finding one of these labels on my window without it having a name and assuming I don't know how far 'down' it is in the tree? Maybe there's an item collection of everything in a window (without heirarchy) that I can run some LINQ against??

If you're wondering why I don't have a name for the labels - it's because they are generated by a data template.

Thanks a lot,

Dan


Solution

  • I made a slight change to the code that @anatoliiG linked in order to return all the child controls of the specified type (instead of the first one):

    private IEnumerable<childItem> FindVisualChildren<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)
                yield return (childItem)child;
    
            foreach (var childOfChild in FindVisualChildren<childItem>(child))
                yield return childOfChild;
        }
    }
    

    With this function you could do something like this:

    var criteriaLabels =
        from cl in FindVisualChildren<Label>(myListBox)
        where cl.Content.ToString() == "criteria"
        select cl;
    
    foreach (var criteriaLabel in criteriaLabels)
    {
        // do stuff...
    }