开发者

How to get a list of all instances of an object on a page

开发者 https://www.devze.com 2023-01-26 17:38 出处:网络
On a Silverlight page ther开发者_如何学JAVAe are a number of instances of a custom control. I can easily get an instance of the custom control by its name:

On a Silverlight page ther开发者_如何学JAVAe are a number of instances of a custom control. I can easily get an instance of the custom control by its name:

MyCustomControl mcc = (MyCustomControl)this.FindName(namestring);

But how could I get a list of all the instances of this custom control on this page?


Add this class to your project:-

public static class VisualTreeEnumeration
{
    public static IEnumerable<DependencyObject> Descendents(this DependencyObject root)
    {
        int count = VisualTreeHelper.GetChildrenCount(root);
        for (int i = 0; i < count; i++)
        {
            var child = VisualTreeHelper.GetChild(root, i);
            yield return child;
            foreach (var descendent in Descendents(child))
                yield return descendent;
        }
    }
}

Now you can use this code:-

 List<MyCustomControl> = this.Descendents().OfType<MyCustomControl>().ToList();


Try something like this

Enumerable.Range(0, VisualTreeHelper.GetChildrenCount(this))
    .Select(i => VisualTreeHelper.GetChild(this, i))
    .Where(c => c is MyUserControl);
0

精彩评论

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