如何在TabItem中获取UserControl?

时间:2019-01-12 09:09:41

标签: c# wpf

XAML代码:

<TabControl TabStripPlacement="Left" Margin="-3,-3,-3,-3" Background="Transparent" SelectionChanged="TabControl_SelectionChanged">
        <TabItem Header="Corn">
            <Grid x:Name="sdfsfd"/>
        </TabItem>
        <TabItem Header="TabItem" >
            <local:CornTab x:Name="cornTab"/>
        </TabItem>
    </TabControl>

CS代码:

private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e) {
        TabItem ti = ((TabControl)sender).SelectedItem as TabItem;
        Console.WriteLine(ti.Header);

        getChildrenOf(ti, 1);
    }

    private void getChildrenOf(DependencyObject dep, int indents) {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dep); i++) {
            var child = VisualTreeHelper.GetChild(dep, i);
            Console.WriteLine($"{new String('\t', indents)}{i}: {child.GetType()}");

            getChildrenOf(child, indents + 1);
        }
    }

当我单击<local:CornTab x:Name="cornTab"/>时我试图检索TabItem,但是无论我做什么,它似乎都不会出现在VisualTreeHelper中,并且打印输出是相同的唯一的区别是TabItem.Header

TabItem
0: System.Windows.Controls.Border
    0: System.Windows.Controls.Grid
        0: MahApps.Metro.Controls.ContentControlEx
            0: System.Windows.Controls.Grid
                0: System.Windows.Controls.ContentPresenter
                    0: System.Windows.Controls.TextBlock
        1: MahApps.Metro.Controls.Underline
            0: System.Windows.Controls.Border
                0: MahApps.Metro.Controls.ClipBorder
                    0: System.Windows.Controls.ContentPresenter
Corn
    0: System.Windows.Controls.Border
        0: System.Windows.Controls.Grid
            0: MahApps.Metro.Controls.ContentControlEx
                0: System.Windows.Controls.Grid
                    0: System.Windows.Controls.ContentPresenter
                        0: System.Windows.Controls.TextBlock
            1: MahApps.Metro.Controls.Underline
                0: System.Windows.Controls.Border
                    0: MahApps.Metro.Controls.ClipBorder
                        0: System.Windows.Controls.ContentPresenter

也许我需要以不同的方式遍历控制树?

1 个答案:

答案 0 :(得分:1)

您不需要遍历视觉树。

TabItemContentControlContentControlContentPropertyAttribute设置为“内容”

System.Windows.Markup.ContentPropertyAttribute

  

指示类型的哪个属性是XAML内容属性。 XAML处理器在处理属性类型的XAML表示形式的XAML子元素时会使用此信息。

因此,您可以简单地将方法更改为此

private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{
    TabItem ti = ((TabControl)sender).SelectedItem as TabItem;
    var content = ti.Content;
    if(content is CornTab cornTab)
    {
        //Do with 'cornTab' whatever you want
    }
}