Search code examples
c#wpffindcontrolstabitem

How do I get a ScrollViewer inside TabItem In WPF


I need to find a ScrollViewer inside current TabItem and then find a WrapPanel inside that ScrollViewer

I tried this:

    TabItem ti = tabControl.SelectedItem as TabItem;
        foreach (ScrollViewer sv in ti.Content)
        {
             foreach (WrapPanel wp in sv.Content) {}
        }

and this

   TabItem ti = tabControl.SelectedItem as TabItem;
        foreach (ScrollViewer sv in ti.Children)
        {
              foreach (WrapPanel wp in sv.Children) {}
        }

But doesn't work


Solution

  • If your tab item contains your scrollviewer directly, you could do the following :

    TabItem ti = tabControl.SelectedItem as TabItem;
    ScrollViewer sv = ti?.Content as ScrollViewer;
    WrapPanel wp = scrollViewer?.Content as WrapPanel;
    

    Another way of accessing your WrapPanel would be to use a function that returns a child/content of a specific type. For instance

        public T FindVisualChildOrContentByType<T>(DependencyObject parent)
            where T : DependencyObject
        {
            if(parent == null)
            {
                return null;
            }
    
            if(parent.GetType() == typeof(T))
            {
                return parent as T;
            }
    
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
    
                if(child.GetType() == typeof(T))
                {
                    return child as T;
                }
                else
                {
                    T result = FindVisualChildOrContentByType<T>(child);
                    if (result != null)
                        return result;
                }
            }
    
            if(parent is ContentControl contentControl)
            {
                return this.FindVisualChildOrContentByType<T>(contentControl.Content as DependencyObject);
            }
    
            return null;
    
        }
    

    Then you would be able to do

    WrapPanel wp = this.FindVisualChildOrContentByType<WrapPanel>(tabItem);
    

    If this is not working, feel free to post your XAML so i can reproduce your exact scenario.