Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

wpf - RelativeSource in DataTemplate works with TabControl but not with TabItem

I am having a TabControl and within it a TabItem having a ContentControl. This ContentControl is applied a datatemplate. The code is here:

<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>

And the data template is:

 <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>

Notice the Image Source in the datatemplate is Tag of TabItem. This isn't working. But if I change the Source to take the Tag of TabControl it works.

Any reason why using Tag of TabItem is not working??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you use something like Snoop to look at the actual Visual Tree getting drawn, you'll see that TabControl's Header and Content are in separate areas, and the TabItems only exist in the Header area, not the Content area. The Content area only holds the currently SelectedItem.

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...