查找所有子控件WPF

时间:2013-02-14 12:36:27

标签: c# wpf

我想找到WPF控件中的所有控件。我看过很多样本,看起来他们都需要将Name作为参数传递或者根本不起作用。

我有现有代码,但无法正常运行:

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

例如,它不会在DataGrid内获得TabItem

有什么建议吗?

2 个答案:

答案 0 :(得分:17)

您可以使用这些。

 public static List<T> GetLogicalChildCollection<T>(object parent) where T : DependencyObject
        {
            List<T> logicalCollection = new List<T>();
            GetLogicalChildCollection(parent as DependencyObject, 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);
                }
            }
        }

您可以在RootGrid中获取子按钮控件,如下所示:

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

答案 1 :(得分:-1)

您可以使用此示例:

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