在WPF中查找所有子控件

12
我希望能够在WPF控件中找到所有的控件。我查看了很多示例,发现它们要么需要传递名称作为参数,要么根本不起作用。
我已经有现有的代码,但它无法正常工作:
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;
      }
    }
  }
}

例如,它无法获取位于选项卡中的数据表格。有什么建议吗?
2个回答

19
您可以使用这些。
 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);
                }
            }
        }

您可以像这样在RootGrid中获取子按钮控件:
 List<Button> button = RootGrid.GetLogicalChildCollection<Button>();

8
逻辑树不包含控件模板中的可视元素。根据定义,您的代码无法找到所有子控件。 - Dennis
1
谢谢,这个有效!它可以获取我的DataGrid,而不是我的代码! - Chrisjan Lodewyks
1
@ChrisjanLodewyks 很高兴听到这个消息。 - Farhad Jabiyev
LogicalTreeHelper.GetChildren() 对我来说很关键。 - ouflak
我在网上搜索了很久才找到这样的解决方案。我尝试了很多方法让它工作,但是一切都失败了。直到我发现了这篇文章,现在一切都正常了。谢谢! - NickGames
显示剩余2条评论

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接