2013-02-14 16 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

तार्किक पेड़ नियंत्रण के खाके से दृश्यों शामिल नहीं है। आपका कोड परिभाषा के अनुसार * सभी * बाल नियंत्रण नहीं ढूंढ सकता है। – Dennis

+1

थैंक्स ने काम किया! यह मेरे अपने डेटा के विपरीत 'डेटाग्रिड' हो जाता है! –

+1

@ChrisjanLodewyks इसे सुनकर खुशी हुई। –

-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; 
      } 
} 
संबंधित मुद्दे