WPF: How do I loop through the all controls in a window?

前端 未结 5 982
无人及你
无人及你 2020-11-27 05:52

How do I loop through the all controls in a window in WPF?

5条回答
  •  無奈伤痛
    2020-11-27 06:28

    I've used the following to get all controls.

        public static IList GetControls(this DependencyObject parent)
        {            
            var result = new List();
            for (int x = 0; x < VisualTreeHelper.GetChildrenCount(parent); x++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(parent, x);
                var instance = child as Control;
    
                if (null != instance)
                    result.Add(instance);
    
                result.AddRange(child.GetControls());
            } 
            return result;
        }
    

提交回复
热议问题