2011-01-12 79 views

回答

1

您可以嘗試下列方法來枚舉Visual Tree。

public static IEnumerable<T> FindVisualChildren<T> 
(DependencyObject depObj, string childName) where T : DependencyObject 
{ 

    if (depObj != null) 
    { 
     for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++) 
     { 

      DependencyObject child = VisualTreeHelper.GetChild(depObj, i); 
      var frameworkElement = child as FrameworkElement; 
      if (child != null && frameworkElement.Name == childName) 
      { 
       yield return (T)child; 
      } 

      foreach (T childOfChild in FindVisualChildren<T>(child, childName)) 
      { 
       yield return childOfChild; 
      } 
     } 
    } 
} 

假設你命名你的文本框"tbInsideStackPanel",使用它像:

foreach (var textBox in FindVisualChildren<TextBox>(this.stackPanel1, 
       "tbInsideStackPanel").ToList()) 
{ 
    textBox.Background = Brushes.Blue; 
}