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

1k Views Asked by At

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

4

There are 4 best solutions below

0
On BEST ANSWER

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...
}
1
On

I don't know whether this will help or not:

If you are looking for a specific label in each stack panel in the listBox, then you could just look for that specific label with its specific name and compare the content.

4
On

Seems like what you're looking for: Find DataTemplate-Generated Elements

2
On

i think this code might be usefull for you:

        foreach (Control control in this.Controls)
        {
            if (control.GetType() == typeof(Label))
                if (control.Text == "yourText")
                {
                    // do your stuff
                }
        }

i used This question as my base