简体   繁体   English

如何获取页面上对象的所有实例的列表

[英]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. 在Silverlight页面上,有许多自定义控件的实例。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM