带有WrapPanel的ListView的选择样式

时间:2016-02-02 18:47:48

标签: c# .net wpf listview listviewitem

我使用的是ListView WrapPanel作为ItemsPanel。我需要更改所选项目的样式 - 使用不同的背景颜色并在所选项目周围添加边框,例如Windows 7的资源管理器。

<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 个答案:

答案 0 :(得分:1)

只需为默认类型和所选类型设计ControlTemplate即可。然后,当选择ListView中的任何项目时,您可以设置Selected 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>