WPF Listview binding to ItemSource?

Viewed 101249

I have the following listview, but it doesn't show the actual records, but only the namespace of the object. I wondered if I need to create the columns in XAML for it to show the records and then bind it to some properties of an object or what is wrong with this?

<ListView
            Name="ListCustomers"
            ItemsSource="{Binding Path=ListOfCustomers}"
            SelectedItem="{Binding Path=SelectedCustomer}"
            SelectionMode="Single"
            IsSynchronizedWithCurrentItem="True"
            HorizontalAlignment="Stretch"
            VerticalAlignment="Stretch"
            MinHeight="100"

            ></ListView>

ListOfCustomers is an ObservableCollection<Customer> type. The actual customers do get loaded into the ObservableCollection, but they are not displayed. What is missing?

3 Answers

You need to select the columns to display as well:

<ListView ItemsSource="{Binding ListOfCustomers}"
          SelectedItem="{Binding Path=SelectedCustomer}"
          ....>
  <ListView.View>
    <GridView>
      <GridViewColumn Width="140" Header="First Name"
         DisplayMemberBinding="{Binding FirstName}"  />
      <GridViewColumn Width="140" Header="Last Name"  
         DisplayMemberBinding="{Binding LastName}" />
      <GridViewColumn Width="140" Header="Email Address"
         DisplayMemberBinding="{Binding Email}" />
      ....
    </GridView>
  </ListView.View>
</ListView>

You could also try

<ListView
.
.
ItemTemplate="{StaticResource CustomerDataTemplate}"
.
.
/>

where CustomerDataTemplate is a DataTemplate for Customer class...

Is it because you have not set the DataContext property of the ListView with the instance that exposes the ListOfCustomers property (which returns the list of items to be displayed) ?

Related