Reputation: 17075
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
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
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