选中后更改ListView图像项的源

时间:2011-09-23 10:44:24

标签: wpf image listview styles

以下是我所追求的样本:

The paging indicator I would like to reproduce

我决定使用ListView实现它(尝试了基于Selector的自定义控件,但我无法输出任何令人满意的内容)。

我的列表显示正常,但我很难找到如何在选择项目时更改图像源。这是我的代码:

<UserControl.Resources>
    <DataTemplate x:Key="PagingIndicatorTemplate">
        <Image Width="20" Height="20">
            <Image.Style>
                <Style TargetType="Image">
                    <Setter Property="Source" Value="/MyProject;component/Resources/Images/ic_paging_button_normal.png" />
                <!-- I guess that's where I need to put my stuff to change the image ? ... -->
                </Style>
            </Image.Style>
        </Image>
    </DataTemplate>
</UserControl.Resources>

    <ListView Name="PagingIndicator" 
              Height="30" 
              ItemTemplate="{DynamicResource PagingIndicatorTemplate}" 
              ItemsSource="{Binding Path=News}">
        <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" />
            </ItemsPanelTemplate>
        </ListView.ItemsPanel>
        <ListView.ItemContainerStyle>
            <Style TargetType="ListBoxItem">
                <Style.Resources>
                    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/>
                </Style.Resources>
            </Style>
        </ListView.ItemContainerStyle>
    </ListView>

2 个答案:

答案 0 :(得分:0)

  1. 有一件事是错的......您正在使用ListView,但目标风格为ListBoxItem。它应该是ListViewItem

  2. Image的样式中,使用DataTrigger检查RelativeSource ListViewItemPath=IsSelected上的绑定(如果为True)并更改{{1图片。

答案 1 :(得分:0)

我决定解决这个问题:

  • 制作两个不同的项目模板(每个模板都有自己的图像,鼠标悬停的样式,鼠标按下,......)
  • 使用IsSelected属性上的触发器更改ListViewItem的Template属性。