How to bind a WPF ListView to a list

As with many controls in .Net, binding is a powerful way to display data from a data source. In this simple example we’ll show you how to bind a ListView to a list of objects.

We’ll start by defining the data we want in the list by creating a class with properties. In this simple example each property will correspond to a single column in the ListView but it’s possible to make it far more fancy/complex than that.

The sample class is given three properties as shown here.

public class Person
  public Int32 Id { get; set; }
  public string Name { get; set; }
  public string City { get; set; }

The highlighted rows in the example below show the ListView we’ll be using. For each column we define what property to use from the class we created above. Note that the ListView doesn’t know anything about the Person class just created, so if you misspell the names you wont get any warnings.

<Window x:Class="OwProjectController.ListViewExample"
        Title="ListViewExample" Height="200" Width="400">
    <ListView Name="PersonListView" Margin="0,0,0,0" >
        <GridView >
          <GridViewColumn Header="Id" Width="80" DisplayMemberBinding="{Binding Id}" />
          <GridViewColumn Header="Name" Width="100" DisplayMemberBinding="{Binding Name}" />
          <GridViewColumn Header="City" Width="100" DisplayMemberBinding="{Binding City}" />

Finally we create a sample list and bind it to the ListView.

It’s not until here, when we connect the data source to the control, that a spelling error from the binding will be noticed when the parser is trying to match the column names. However, a misspelled name only results in an empty column, nothing else. If you misspell all the binding names for all columns the rows will still be added but nothing will be displayed in your ListView.

List<Person> personList = new List<Person>();
personList.Add(new Person() { Id = 1, Name = "Charle Mange", City = "Seattle"});
personList.Add(new Person() { Id = 2, Name = "John Knox", City = "New York" });
personList.Add(new Person() { Id = 3, Name = "Michael Doher", City = "Washington" });
PersonListView.ItemsSource = personList;

The result will look like this:
WPF ListView