2013-02-14 55 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; 
      } 
}