rem
rem

Reputation: 17075

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

On a Silverlight page there 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?

Upvotes: 0

Views: 147

Answers (2)

AnthonyWJones
AnthonyWJones

Reputation: 189495

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

Upvotes: 2

Dean Chalk
Dean Chalk

Reputation: 20471

Try something like this

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

Upvotes: 1

Related Questions