rem
rem

Reputation: 17055

How to iterate through set of custom control objects in WPF?

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 ???)
{
 ....

}

Upvotes: 1

Views: 895

Answers (2)

Mark OMeara
Mark OMeara

Reputation: 1

Great solution,for those who want a generic version of it - a slight alteration as below may be of assistance:

public static class ControlFinder<T>
{
    public static IEnumerable<T> FindControl(DependencyObject root)
    {
        int count = VisualTreeHelper.GetChildrenCount(root);
        for (int i = 0; i < count; ++i)
        {
            dynamic child = VisualTreeHelper.GetChild(root, i);
            if (child is T)
            {
                yield return (T)child;
            }
            else
            {
                foreach (T found in FindControl(child))
                {
                    yield return found;
                }
            }
        }
    }
}

It can be called by:

IEnumerable<MyType> mytypes = ControlFinder<MyType>.FindControl(root);

Upvotes: 0

Nir
Nir

Reputation: 29594

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;
            }
        }
    }
}

Upvotes: 3

Related Questions