How to get a list of all instances of an object on a page
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);
精彩评论