How can I find WPF controls by name or type?

后端 未结 18 2946
庸人自扰
庸人自扰 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条回答
  •  梦毁少年i
    2020-11-21 04:43

    Here's my code to find controls by Type while controlling how deep we go into the hierarchy (maxDepth == 0 means infinitely deep).

    public static class FrameworkElementExtension
    {
        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;
                foreach (var c in (IEnumerable)o.GetType()
                    .GetProperty(childrenProperty).GetValue(o, null))
                {
                    if (c.GetType().FullName == childType.FullName)
                        list.Add(c);
                    if (maxDepth == 0 || depth < maxDepth)
                        list.AddRange(RecursiveFindControls(
                            c, childType, depth + 1, maxDepth));
                }
            }
            return list.ToArray();
        }
    }
    
        

    提交回复
    热议问题