How to: Style a Row in a ListView That Implements a GridView


This example shows how to style a row in a ListView control that implements a GridViewView mode.

You can style a row in a ListView control by setting an ItemContainerStyle on the ListView control. Set the style for its items that are represented as ListViewItem objects. The ItemContainerStyle references the ControlTemplate objects that are used to display the row content.

The complete sample, which the following examples are extracted from, displays a collection of song information that is stored in an XML database. Each song in the database has a rating field and the value of this field specifies how to display a row of song information.

The following example shows how to define ItemContainerStyle for the ListViewItem objects that represent the songs in the song collection. The ItemContainerStyle references ControlTemplate objects that specify how to display a row of song information.

    <Style TargetType="{x:Type ListViewItem}"  >
      <Setter Property="Template"
            Value="{StaticResource Default}"/>
        <DataTrigger Binding="{Binding XPath=@Rating}" Value="5">
				<Setter Property="Template" 
                Value="{StaticResource StronglyRecommended}"/>
        <DataTrigger Binding="{Binding XPath=@Rating}" Value="4">
          <Setter Property="Template" 
                Value="{StaticResource Recommended}"/>

The following example shows a ControlTemplate that adds the text string "Strongly Recommended" to the row. This template is referenced in the ItemContainerStyle and displays when the song's rating has a value of 5 (five). The ControlTemplate includes a GridViewRowPresenter object that lays out the contents of the row in columns as defined by the GridView view mode.

    <ControlTemplate x:Key="StronglyRecommended" 
                     TargetType='{x:Type ListViewItem}'>
      <StackPanel Background="Beige">
        <GridViewRowPresenter Content="{TemplateBinding Content}"
           Columns="{TemplateBinding GridView.ColumnCollection}"/>
        <TextBlock Background="LightBlue" Text="Strongly Recommended" />

The following example defines GridView.

    <GridView ColumnHeaderContainerStyle="{StaticResource MyHeaderStyle}">
      <GridViewColumn Header="Name" 
                      DisplayMemberBinding="{Binding XPath=@Name}" 
      <GridViewColumn Header="Time" 
                      DisplayMemberBinding="{Binding XPath=@Time}" 
      <GridViewColumn Header="Artist"  
                      DisplayMemberBinding="{Binding XPath=@Artist}" 
                      Width="80" />
      <GridViewColumn Header="Disk" 
                      DisplayMemberBinding="{Binding XPath=@Disk}"  

How-to Topics
ListView Overview
Styling and Templating