How to bind ContentTemplate in a ListView in WPF

1.3k views Asked by At

I have simplified the problem a bit, but I need to change the style and ControlTemplate for a ListView item while still binding to the ListView ItemSource.

Here is my ListView definition:

<ListView x:Name="MyListView"
          ItemsSource="{Binding ListOfStrings}"
          ItemContainerStyle="{StaticResource MyListViewItemStyle}"/>

And the ItemContainerStyle:

<Style x:Key="MyListViewItemStyle" TargetType="ListViewItem">
     <Setter Property="Template">
          <Setter.Value>
               <ControlTemplate TargetType="ListViewItem">
                    <DataTemplate>
                         <TextBlock x:Name="txtValue" Text="{Binding Mode=TwoWay}" />
                    </DataTemplate>
               </ControlTemplate>
          </Setter.Value>
     </Setter>
</Style>

The ItemSource of the ListView is of type: List<string>

I need the TextBlock (txtValue) to display an item through the Binding to the ItemSource.

The ListView contains the correct amount of items, but how do I bind the TextBlock?

I need to do this in a WPF Universal Windows Platform application. I tested the same code in a normal WPF windows application and the code works correctly. But in the UWP application the ContentTemplate does not bind correctly.

I am sure I am missing something simple.

2

There are 2 answers

3
Artyom Shmarlovsky On

Try this:

<Style x:Key="MyListViewItemStyle" TargetType="ListViewItem">
 <Setter Property="Template">
      <Setter.Value>
           <ControlTemplate TargetType="ListViewItem">
                     <TextBlock x:Name="txtValue" Text="{Binding }" />
           </ControlTemplate>
      </Setter.Value>
 </Setter>

Two-way binding requires Path or XPath.

The root of a Template content section cannot contain an element of type 'System.Windows.DataTemplate'. Only FrameworkElement and FrameworkContentElement types are valid.

0
Reynier Booysen On

Found a solution here. Still trying to figure out why it works, but it does.