Get and Iterate through Controls from a TabItem?

后端 未结 3 1239
囚心锁ツ
囚心锁ツ 2020-12-19 18:30

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 SelectedT

相关标签:
3条回答
  • 2020-12-19 18:48

    May be method of this kind will help you:

    public static IEnumerable<T> FindChildren<T>(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<T>(child))
          {
            yield return descendant;
          }
        }
      }
    }
    

    See full article (Finding Elements in the WPF Tree) here.

    0 讨论(0)
  • 2020-12-19 18:54

    for me VisualTreeHelper.GetChildrenCount always returns 0 for tab control, I had to use this method instead

     public static List<T> ObtenerControles<T>(DependencyObject parent)
        where T : DependencyObject
        {
            List<T> result = new List<T>();           
            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<T>(child as DependencyObject))
                    {
                        result.Add(other);
                    }
                }
            }
    
            return result;
        }
    
    0 讨论(0)
  • 2020-12-19 19:07

    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;
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题