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

时间:2020-12-15 15:05:31

I have a ListBox that use my custom ItemTemplate. I want to set Visibility property in my TextBlock (inside my template) depending on selected item. I think of doing it using triggers. But how can I know inside my template if current item is selected or not?

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

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

edit: It works, thanks! Code:

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

            <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 个解决方案

#1


2  

Using a RelativeSource binding with AncestorType being ListBoxItem.

使用与AncestorType为ListBoxItem的RelativeSource绑定。

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

(May want to reverse the logic and Collapse on False instead, avoids the default value Setter)

(可能想要反转逻辑而反而折叠为False,避免默认值Setter)

#1


2  

Using a RelativeSource binding with AncestorType being ListBoxItem.

使用与AncestorType为ListBoxItem的RelativeSource绑定。

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

(May want to reverse the logic and Collapse on False instead, avoids the default value Setter)

(可能想要反转逻辑而反而折叠为False,避免默认值Setter)