views:

263

answers:

1

In a window of my WPF application I have a number of objects which dirived from a custom control:

...
<MyNamespace:MyCustControl x:Name="x4y3" />
<MyNamespace:MyCustControl x:Name="x4y4" />
<MyNamespace:MyCustControl x:Name="x4y5" />
<MyNamespace:MyCustControl x:Name="x4y6" />
<MyNamespace:MyCustControl x:Name="x4y7" />
...

In my code I can easily reference each of them individually by name:

x1y1.IsSelected = true;

How, in my code, could I iterate through whole set of them in loop?

foreach (... in ???)
{
 ....

}
+3  A: 

You can use VisualTreeHelper or LogicalTreeHelper to scan all the content of your Window or Page and locate the specific controls (maybe by checking if their type is MyCustControl

private IEnumerable<MyCustControl> FindMyCustControl(DependencyObject root)
{
    int count = VisualTreeHelper.GetChildrenCount(root);
    for (int i = 0; i < count; ++i)
    {
        DependencyObject child = VisualTreeHelper.GetChild(root, i);
        if (child is MyCustControl)
        {
            yield return (MyCustControl)child;
        }
        else
        {
            foreach (MyCustControl found in FindMyCustControl(child))
            {
                yield return found;
            }
        }
    }
}
Nir
+1 - I have deleted my answer because yours was 100x better :)
IanR
Thanks a lot! This is exactly what I need. But could you help me get it work (I didn't manage so far). What I'm trying to do is: put this code in the code-behind file, inside the foreach loop put "found.IsSelected = true;" and call a method FindMyCustControl(this); in the window initializer. But it doesn't work. What am I doing wrong?
rem
This will only work after the visual tree is built, if you try this too early in the window's life parts of the tree may still be missing.Generally you shouldn't try to walk the visual tree before the Loaded event but you can try to call ApplyTemplate on any element that is missing its visual children.
Nir
OK, Nir. I will explore it and give a try. Thank you for your help!
rem