DataTemplate中的RelativeSource可以与TabControl一起使用,但不能与TabItem一起使用。

4

我有一个TabControl,在其中有一个TabItem,其中包含一个ContentControl。这个ContentControl应用了一个数据模板。代码如下:

<TabControl x:Name="tabControl1" Tag="Giving URI here works">
                        <TabItem x:Name="tabItem1" Tag="Giving URI here doesnt work">
                            <ContentControl ContentTemplate="{StaticResource myOptionsDataTemplate}">
                                <StackPanel>
                                    <TextBlock Text="Some Text" />
                                </StackPanel>
                            </ContentControl>
                        </TabItem>
</TabControl>

数据模板如下:

 <DataTemplate x:Key="myOptionsDataTemplate">
        <Border>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                </Grid.RowDefinitions>
                <DockPanel LastChildFill="True">
                    <Image Source="{Binding Path=Tag, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TabItem}}}"
                            Width="32" Height="32"
                            HorizontalAlignment="Left"
                            VerticalAlignment="Top"
                            DockPanel.Dock="Left"
                            Margin="0,0,4,0"/>
                    <Label Content="Some Text"
                            />
                </DockPanel>
                <ContentControl Grid.Row="2" Content="{TemplateBinding ContentControl.Content}"/>
            </Grid>
        </Border>
    </DataTemplate>

请注意 DataTemplate 中的图片源是 TabItem 的标签。但这样不起作用。但如果我将源更改为使用 TabControl 的标签,则可以正常工作。

为什么使用 TabItem 的标签不起作用?

1个回答

4
如果你使用类似Snoop这样的工具来查看实际绘制的可视树,你会发现TabControl的Header和Content位于不同的区域,而TabItems仅存在于Header区域,而不是Content区域。 Content区域仅保存当前选定的项。

enter image description here


谢谢Rachel。我错过了一个如此明显的事情。现在我更好地理解了TabControl的奇怪行为。 - digitguy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接