Home > database >  How to add a button to each row in List View Data Template in c# wpf
How to add a button to each row in List View Data Template in c# wpf

Time:10-10

I have this code as my list view:

<ListView x:Name="listViewPhotoLibrary">
 <ListView.ItemTemplate>
  <DataTemplate>
   <Grid>
    <Grid.ColumnDefinitions>
     <ColumnDefinition Width="47"/>
     <ColumnDefinition Width="100"/>
    </Grid.ColumnDefinitions>
    <Button Content="X"/>
    <TextBlock Foreground="Teal"/>
   </Grid>
  </DataTemplate>
 </ListView.ItemTemplate>
</ListView>

and i use a list of string as its item source

List<string> libraries = new List<string>(Properties.Settings.Default.Paths.Split(new char[] { ';' }));
            libraries = libraries.Where(s => !string.IsNullOrEmpty(s)).Distinct().ToList();
            listViewPhotoLibrary.ItemsSource = libraries;

My problem is that the list view is not showing the text. this is what i get.

what am I doing wrong and what are some good reads for understanding data templates?

CodePudding user response:

The element in the grid are missing a column number, also the text box has no content, try this:

<Button Grid.Column="0" Content="X"/>
<TextBlock Grid.Column="1" Foreground="Teal" Text="Some text"/>

To display the actual content of the items in the list, you need to use the Binding object, in your case, since the object are just string the binding declaration is simple:

<TextBlock Grid.Column="1" Foreground="Teal" Text="{Binding}"/>

Which is equivalent to:

<TextBlock Grid.Column="1" Foreground="Teal" Text="{Binding Path=."/>

The documentation is a good start, read well noted WPF questions on SO is also a good idea.

  • Related