如何知道ItemTemplate中是否选择了项目?

时间:2013-09-10 22:27:36

标签: c# wpf xaml datatemplate itemtemplate

我有ListBox使用我的自定义ItemTemplate。我想根据所选项目在Visibility(我的模板内)中设置TextBlock属性。我想用触发器做它。但是,我如何知道我的模板中是否选择了当前项目?

<DataTemplate x:Key="myTemplate">
    <StackPanel Orientation="Horizontal">
        <Image Tag="{Binding priority}" Loaded="SetIconPriority"/>
        <Image Tag="{Binding alarm}" Loaded="SetIconAlarm"/>
        <!-- I want this TextBlock to be visible only when item is selected -->
        <TextBlock Text="{Binding description}"/>
    </StackPanel>
</DataTemplate>

编辑: 它有效,谢谢!代码:

            <TextBlock Grid.Column="2" Grid.Row="1" Text="{Binding opis}">
                <TextBlock.Style>
                    <Style TargetType="TextBlock">
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=ListBoxItem}}" Value="False">
                                <Setter Property="Visibility" Value="Collapsed"/>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </TextBlock.Style>
            </TextBlock>

1 个答案:

答案 0 :(得分:2)

使用RelativeSource绑定AncestorTypeListBoxItem

<DataTrigger Binding="{Binding IsSelected,
                               RelativeSource={RelativeSource AncestorType=ListBoxItem}}"
             Value="True">

(可能想要反转逻辑而Collapse代替False,避免使用默认值Setter