简体   繁体   English

查找所有子控件 WPF

[英]Finding ALL child controls WPF

I would like to find all of the controls within a WPF control.我想在 WPF 控件中找到所有控件。 I have had a look at a lot of samples and it seems that they all either require a Name to be passed as parameter or simply do not work.我看过很多示例,似乎它们都需要将 Name 作为参数传递,或者根本不起作用。

I have existing code but it isn't working properly:我有现有代码,但无法正常工作:

public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
  if (depObj != null)
  {
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
    {
      DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
      if (child != null && child is T)
      {
        yield return (T)child;
      }

      foreach (T childOfChild in FindVisualChildren<T>(child))
      {
        yield return childOfChild;
      }
    }
  }
}

For instance it will not get a DataGrid within a TabItem .例如,它不会在TabItem获得DataGrid

Any suggestions?有什么建议么?

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 fe like that:您可以像这样在 RootGrid fe 中获得子按钮控件:

 List<Button> button = RootGrid.GetLogicalChildCollection<Button>();

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;
           }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM