How can I find WPF controls by name or type?

后端 未结 18 3610
庸人自扰
庸人自扰 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:44

    If you want to find ALL controls of a specific type, you might be interested in this snippet too

        public static IEnumerable FindVisualChildren(DependencyObject parent) 
            where T : DependencyObject
        {
            int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < childrenCount; i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
    
                var childType = child as T;
                if (childType != null)
                {
                    yield return (T)child;
                }
    
                foreach (var other in FindVisualChildren(child))
                {
                    yield return other;
                }
            }
        }
    

提交回复
热议问题