列表框在选择时更改图像

时间:2019-05-22 11:36:13

标签: wpf xaml

我有一个列表框,其中SelectionMode设置为Single,项目模板如下所示:

            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Vertical" Width="100" Margin="10" Cursor="Hand" >
                        <Image Source="/Assets/Images/folder_80closed.png" HorizontalAlignment="Center" />
                        <TextBox Text="{Binding Name}" BorderThickness="0" TextAlignment="Center" HorizontalAlignment="Center"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>

是否可以根据是否选择此项来更改XAML中的图像Source属性 的值?像是波纹管,选择了item4。

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以在当前ListBoxItem的IsSelected属性上使用带有DataTrigger的图像样式:

<Image HorizontalAlignment="Center">
    <Image.Style>
        <Style TargetType="Image">
            <Setter Property="Source"
                    Value="/Assets/Images/folder_80closed.png"/>

            <Style.Triggers>
                <DataTrigger
                    Binding="{Binding IsSelected,
                             RelativeSource={RelativeSource AncestorType=ListBoxItem}}"
                    Value="True">
                    <Setter Property="Source"
                            Value="/Assets/Images/some_other_image.png"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Image.Style>
</Image>