从TabItem获取并迭代控件?

如何获取嵌套在Tabitem中的所有控件/ UIElements(来自TabControl)?

我尝试了一切,但无法得到它们。

(设置SelectedTab):

private TabItem SelectedTab = null; private void tabControl1_SelectionChanged(object sender, SelectionChangedEventArgs e) { SelectedTab = (TabItem)tabControl1.SelectedItem; } 

现在我需要这样的东西:

  private StackPanel theStackPanelInWhichLabelsShouldBeLoaded = null; foreach (Control control in tabControl.Children /*doesnt exist*/, or tabControl.Items /*only TabItems*/, or /*SelectedTab.Items ??*/ ) //I Have no plan { if(control is StackPanel) { theStackPanelInWhichLabelsShouldBeLoaded = control; //Load Labels in the Stackpanel, thats works without problems } } 

在Silvermind之后:执行此操作,Count始终为1:

  UpdateLayout(); int nChildCount = VisualTreeHelper.GetChildrenCount(SelectedTab); 

TabControl具有Items属性(派生自ItemsControl),它返回所有TabItems – http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.items.aspx 。 或者你可以遍历可视树:

 var firstStackPanelInTabControl = FindVisualChildren(tabControl).First(); 

使用:

 public static IEnumerable FindVisualChildren(DependencyObject rootObject) where T : DependencyObject { if (rootObject != null) { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(rootObject); i++) { DependencyObject child = VisualTreeHelper.GetChild(rootObject, i); if (child != null && child is T) yield return (T)child; foreach (T childOfChild in FindVisualChildren(child)) yield return childOfChild; } } } 

可能是这种方法会帮助你:

 public static IEnumerable FindChildren(this DependencyObject source) where T : DependencyObject { if (source != null) { var childs = GetChildObjects(source); foreach (DependencyObject child in childs) { //analyze if children match the requested type if (child != null && child is T) { yield return (T) child; } //recurse tree foreach (T descendant in FindChildren(child)) { yield return descendant; } } } } 

请在此处查看完整文章(在WPF树中查找元素)。

对我来说,VisualTreeHelper.GetChildrenCount总是为标签控件返回0,我不得不使用这个方法代替

  public static List ObtenerControles(DependencyObject parent) where T : DependencyObject { List result = new List(); if (parent != null) { foreach (var child in LogicalTreeHelper.GetChildren(parent)) { var childType = child as T; if (childType != null) { result.Add((T)child); } foreach (var other in ObtenerControles(child as DependencyObject)) { result.Add(other); } } } return result; }