Finding ALL child controls WPF

后端 未结 2 1951
被撕碎了的回忆
被撕碎了的回忆 2020-12-01 18:33

I would like to find all of the controls within a WPF control. I have had a look at a lot of samples and it seems that they all either require a Name to be passed as paramet

相关标签:
2条回答
  • 2020-12-01 19:17

    You can use these.

     public static List<T> GetLogicalChildCollection<T>(this DependencyObject parent) where T : DependencyObject
            {
                List<T> logicalCollection = new List<T>();
                GetLogicalChildCollection(parent, logicalCollection);
                return logicalCollection;
            }
    
     private static void GetLogicalChildCollection<T>(DependencyObject parent, List<T> logicalCollection) where T : DependencyObject
            {
                IEnumerable children = LogicalTreeHelper.GetChildren(parent);
                foreach (object child in children)
                {
                    if (child is DependencyObject)
                    {
                        DependencyObject depChild = child as DependencyObject;
                        if (child is T)
                        {
                            logicalCollection.Add(child as T);
                        }
                        GetLogicalChildCollection(depChild, logicalCollection);
                    }
                }
            }
    

    You can get child button controls in RootGrid f.e like that:

     List<Button> button = RootGrid.GetLogicalChildCollection<Button>();
    
    0 讨论(0)
  • 2020-12-01 19:30

    You can use this Example:

    public Void HideAllControl()
    { 
               /// casting the content into panel
               Panel mainContainer = (Panel)this.Content;
               /// GetAll UIElement
               UIElementCollection element = mainContainer.Children;
               /// casting the UIElementCollection into List
               List < FrameworkElement> lstElement =    element.Cast<FrameworkElement().ToList();
    
               /// Geting all Control from list
               var lstControl = lstElement.OfType<Control>();
               foreach (Control contol in lstControl)
               {
                   ///Hide all Controls 
                   contol.Visibility = System.Windows.Visibility.Hidden;
               }
    }
    
    0 讨论(0)
提交回复
热议问题