2016-02-02 34 views
0

我使用的ListViewWrapPanel作为其ItemsPanel。我需要更改所选项目的样式 - 使用不同的背景颜色,并在所选项目周围添加边框,如Windows 7的Explorer。带有WrapPanel的ListView的选择样式

<ListView ItemsSource="{Binding Items}" ScrollViewer.HorizontalScrollBarVisibility="Disabled"> 
    <ListView.ItemsPanel> 
     <ItemsPanelTemplate> 
      <WrapPanel IsItemsHost="True" /> 
     </ItemsPanelTemplate> 
    </ListView.ItemsPanel> 

    <ListView.ItemTemplate> 
     <DataTemplate> 
      <StackPanel Orientation="Vertical" Margin="10"> 
       <Rectangle Width="100" Height="100" Fill="Pink" /> 
       <TextBlock Text="{Binding Caption}" Margin="0,10,0,0" /> 
      </StackPanel> 
     </DataTemplate> 
    </ListView.ItemTemplate> 
</ListView> 

回答

1

只是为默认类型和选定类型设计ControlTemplate。然后,您可以在ListView中的任何项目被选中时设置选择ControlTemplate,否则保持默认类型。

<Window.Resources> 
    <ControlTemplate x:Key="DEFAULT"> 
     <StackPanel Orientation="Vertical" Margin="10"> 
      <Rectangle Width="100" Height="100" Fill="Green" /> 
      <TextBlock Text="{Binding Caption}" Margin="0,10,0,0" /> 
     </StackPanel> 
    </ControlTemplate> 
    <ControlTemplate x:Key="SELECTED_TYPE"> 
     <Border BorderBrush="Gray" BorderThickness="1"> 
     <StackPanel Orientation="Vertical" Margin="10"> 
      <Rectangle Width="100" Height="100" Fill="Pink" /> 
      <TextBlock Text="{Binding Caption}" Margin="0,10,0,0" /> 
     </StackPanel> 
     </Border> 
    </ControlTemplate> 

    <Style x:Key="ListItemStyle" TargetType="{x:Type ListBoxItem}"> 
     <Setter Property="Background" Value="White"/> 
     <Style.Triggers> 
      <Trigger Property="IsSelected" Value="True"> 
       <Setter Property="Template" Value="{StaticResource SELECTED_TYPE}"/> 
       <Setter Property="Background" Value="Orange"/> 
      </Trigger> 
      <Trigger Property="IsSelected" Value="False"> 
       <Setter Property="Template" Value="{StaticResource DEFAULT}"/> 
      </Trigger> 
     </Style.Triggers> 
    </Style> 
</Window.Resources> 

<ListView ItemsSource="{Binding Items}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" 
      ItemContainerStyle="{StaticResource ListItemStyle}"> 
    <ListView.ItemsPanel> 
     <ItemsPanelTemplate> 
      <WrapPanel IsItemsHost="True" /> 
     </ItemsPanelTemplate> 
    </ListView.ItemsPanel> 
</ListView>