Search code examples
c#wpfdynamicdatatemplate

How to access dynamic control WPF in DataTemplate


I created a tabcontrol with TabItem dynamic, and each TabItem with a button to close it, but just want that button visible when the TabItem is selected. But I can not access the control inside the DataTemplate

<TabControl Name="dynamicTab" ItemsSource="{Binding}" Margin="0,85,0,0">
    <TabControl.Resources>
        <DataTemplate x:Key="TabHeader" DataType="TabItem">
                    <DockPanel>
                        <Button 
                            Focusable="False"
                            BorderThickness="0" 
                            Background="Transparent"
                            BorderBrush="Transparent"
                            Padding="-4"
                            Height="10"
                            Width="10"
                            Name="btnDelete" Visibility="Hidden" DockPanel.Dock="Right" Margin="5,0,0,0" Click="btnDelete_Click" 
                            CommandParameter="{Binding RelativeSource={RelativeSource AncestorType={x:Type TabItem}}, Path=Name}">
                            <Image Name="imgButtonClose" Source="/Recursos;component/Imagens/close16x16.png" Height="10" Width="10"/>
                        </Button>
                        <TextBlock Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type TabItem}}, Path=Header}" />
                    </DockPanel>
        </DataTemplate>
    </TabControl.Resources>
</TabControl>

Solution

  • Just use the binding on the IsSelected property of ancestoral TabItem:

    <BooleanToVisibilityConverter x:Key="boolToVisibilityConverter"/>
    ...
    <Button ...
            Name="btnDelete" 
            Visibility="{Binding RelativeSource={RelativeSource AncestorType={x:Type TabItem}}, Path=IsSelected, Converter={StaticResource boolToVisibilityConverter}"> 
            ...
    </Button>
    

    If you have no problems with this binding:

    CommandParameter="{Binding RelativeSource={RelativeSource AncestorType={x:Type TabItem}}, Path=Name}"
    

    then the proposed code should work.