Get and Iterate through Controls from a TabItem?

eMi picture eMi · Mar 20, 2012 · Viewed 8.7k times · Source

How to get all the Controls/UIElements which are nested in a Tabitem (from a TabControl)?

I tried everything but wasn't able to get them.

(Set the SelectedTab):

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

Now I need something like this:

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

After Silvermind: Doing this, the Count is always 1:

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

Answer

Nikolay picture Nikolay · Mar 20, 2012

TabControl has Items property (derived from ItemsControl), which returns all TabItems - http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.items.aspx. Or you can traverse visual tree:

var firstStackPanelInTabControl = FindVisualChildren<StackPanel>(tabControl).First();

Using:

public static IEnumerable<T> FindVisualChildren<T>(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<T>(child))
        yield return childOfChild;
    }
  }
}