开发者

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

开发者 https://www.devze.com 2022-12-15 16:51 出处:网络
In a window of my WPF application I have a number of objects which dirived from a custom control: ... <MyNamespace:MyCustControl x:Name=\"x4y3\" />

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" />
...开发者_Go百科

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

}


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


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消