How do I get a ScrollViewer inside TabItem In WPF

时间:2018-09-22 22:47:32

标签: c# wpf find controls tabitem

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

1 个答案:

答案 0 :(得分:0)

如果您的标签项直接包含您的scrollviewer,则可以执行以下操作:

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

访问WrapPanel的另一种方式是使用返回特定类型的子项/内容的函数。例如

    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;

    }

那么您就可以

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

如果这不起作用,请随时发布您的XAML,以便我可以重现您的确切情况。

相关问题