2013-02-14 49 views
9

我想查找WPF控件中的所有控件。我看了很多样本​​,似乎他们都需要一个名称作为参数传递或根本不工作。查找所有子控件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; 
     } 
    } 
    } 
} 

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

有什么建议吗?

回答

12

您可以使用这些。

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子按钮控件f.e这样的:

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

逻辑树不包含控件模板的视觉效果。您的代码根据定义无法找到* all *子控件。 – Dennis 2013-02-14 13:24:14

+1

Thanx工作!它获取我的'DataGrid',不像我自己的代码! – 2013-02-14 13:26:28

+1

@ChrisjanLodewyks很高兴听到它。 – 2013-02-14 13:32:16

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