ListViewItem custom template: ContentPresenter stays empty

Modus Operandi picture Modus Operandi · Jan 14, 2013 · Viewed 17k times · Source

I have the following ListView in my code. views:GameCard is a custom UserControl and {Binding} is a valid DataContext object with three items. Without the custom ItemContainerStyle everything works perfectly — the list shows three GameCards with correct info, etc. As soon as I add the ItemContainerStyle part, I get nothing but three "ABCD"s; so the data is still loaded correctly, but my UserControl is no longer displayed (I only added the "ABCD" to check if the data was there, as otherwise I got nothing but empty box).

Every piece of info I could find online seems to indicate that just putting a ContentPresenter element in the template should work, but it doesn't seem to in this case. What am I missing?

<ListView Grid.Row="1" ItemsSource="{Binding}" BorderThickness="0,0,1,0"
              ScrollViewer.HorizontalScrollBarVisibility="Disabled">
    <ListView.Background>
        <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
            <GradientStop Color="#FF614B4B" Offset="0"/>
            <GradientStop Color="#FFDA7070" Offset="1"/>
        </LinearGradientBrush>
    </ListView.Background>
  <ListView.ItemsPanel>
    <ItemsPanelTemplate>
      <WrapPanel />
    </ItemsPanelTemplate>
  </ListView.ItemsPanel>
  <ListView.ItemTemplate>
    <DataTemplate>
      <views:GameCard />
    </DataTemplate>
  </ListView.ItemTemplate>
  <ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate>
            <Grid>
              <TextBlock Text="ABCD" />
              <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
            </Grid>
          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Style>
  </ListView.ItemContainerStyle>
</ListView>

Answer

Clemens picture Clemens · Jan 14, 2013

You need to set the TargetType of your ControlTemplate. And in order to make your ItemTemplate work, you'd also need to bind the Content and ContentTemplate properties.

<ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListViewItem">
                    <Grid>
                        ....
                        <ContentPresenter
                            Content="{TemplateBinding Content}"
                            ContentTemplate="{TemplateBinding ContentTemplate}"
                            ... />
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ListView.ItemContainerStyle>