【问题标题】:Change a ListView image item's source when selected选择时更改 ListView 图像项的源
【发布时间】:2011-09-23 10:44:23
【问题描述】:

以下是我所追求的示例:

我决定使用 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>

【问题讨论】:

  • 你从哪里加载图像源?项目是否包含图像源路径或这是静态资源数据?
  • 我的想法是将所有图像路径存储在 Resources Collection 数组中,然后将其绑定到 ListView SelectedItemIndex like Source="{Binding ImageSources[SelectedItemIndex], Mode=Default}"
  • 我正在从如下路径加载图像:/MyProject;component/Resources/Images/ic_paging_button_normal.png
  • 基本上每个列表项都有两个不同的图像?您可以添加 DataTrigger 并更新 Source 属性取决于数据项状态甚至列表的 SelectedIndex
  • 你会怎么做? (我对 WPF 很陌生)此外,不能修改数据项状态以包含“IsSelected”属性,唯一的选择是例如基于列表的 SelectedIndex。

标签: wpf image listview styles


【解决方案1】:
  1. 有一个问题...您正在使用ListView,但将样式定位到ListBoxItem。应该是ListViewItem

  2. Image 的样式中,使用DataTrigger 检查RelativeSource ListViewItemPath=IsSelected 上的绑定(如果为真)并更改图像的Source

【讨论】:

    【解决方案2】:

    我决定这样解决问题:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多