如何在DataTemplate中访问动态控件WPF

时间:2014-07-02 14:06:50

标签: c# wpf dynamic datatemplate

我使用TabItem动态创建了一个tabcontrol,每个TabItem都有一个按钮来关闭它,但只是希望在选择TabItem时该按钮可见。 但是我无法访问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>

1 个答案:

答案 0 :(得分:2)

只需对祖先TabItem的IsSelected属性使用绑定:

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

如果您对此绑定没有任何问题:

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

那么建议的代码应该可行。