How can I find WPF controls by name or type?

后端 未结 18 2934
庸人自扰
庸人自扰 2020-11-21 04:23

I need to search a WPF control hierarchy for controls that match a given name or type. How can I do this?

18条回答
  •  臣服心动
    2020-11-21 04:54

    exciton80... I was having a problem with your code not recursing through usercontrols. It was hitting the Grid root and throwing an error. I believe this fixes it for me:

    public static object[] FindControls(this FrameworkElement f, Type childType, int maxDepth)
    {
        return RecursiveFindControls(f, childType, 1, maxDepth);
    }
    
    private static object[] RecursiveFindControls(object o, Type childType, int depth, int maxDepth = 0)
    {
        List list = new List();
        var attrs = o.GetType().GetCustomAttributes(typeof(ContentPropertyAttribute), true);
        if (attrs != null && attrs.Length > 0)
        {
            string childrenProperty = (attrs[0] as ContentPropertyAttribute).Name;
            if (String.Equals(childrenProperty, "Content") || String.Equals(childrenProperty, "Children"))
            {
                var collection = o.GetType().GetProperty(childrenProperty).GetValue(o, null);
                if (collection is System.Windows.Controls.UIElementCollection) // snelson 6/6/11
                {
                    foreach (var c in (IEnumerable)collection)
                    {
                        if (c.GetType().FullName == childType.FullName)
                            list.Add(c);
                        if (maxDepth == 0 || depth < maxDepth)
                            list.AddRange(RecursiveFindControls(
                                c, childType, depth + 1, maxDepth));
                    }
                }
                else if (collection != null && collection.GetType().BaseType.Name == "Panel") // snelson 6/6/11; added because was skipping control (e.g., System.Windows.Controls.Grid)
                {
                    if (maxDepth == 0 || depth < maxDepth)
                        list.AddRange(RecursiveFindControls(
                            collection, childType, depth + 1, maxDepth));
                }
            }
        }
        return list.ToArray();
    }
    
        

    提交回复
    热议问题