Click here to Skip to main content
15,886,519 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Trying to learn how to bind list to ListView . My code populates the ListView but rather than put the contents of the Client object it repeatedly puts the name of the class. (Note: searched for related entries but couldn't grasp the possible solution)
WPF data binding - binding List to ListView

(XAML)
XML
<ListView x:Name="lvClients" HorizontalAlignment="Left" Height="300" VerticalAlignment="Top" Width="300" >
     <ListView.View>
         <GridView>
             <GridViewColumn/>
         </GridView>
     </ListView.View>
</ListView>


(Code behind)
C#
List<Client> names = new List<Client>();

public ucDatabindingListView()
{
     InitializeComponent();
     names.Add(new Client(1, "John"));
     names.Add(new Client(2, "Jane"));

     lvClients.ItemsSource = names; // This doesn't work!
}


(another c# class)
C#
public class Client
 {
     public int ID { get; set; }

     public string Name { get; set; }

     public Client(int id, string name)
     {
         this.ID = id;
         this.Name = name;
     }
 }
Posted
Updated 7-Oct-14 13:30pm
v2
Comments
[no name] 7-Oct-14 19:46pm    
You need to create an item template, http://www.wpf-tutorial.com/listview-control/listview-data-binding-item-template/
needyt 7-Oct-14 20:02pm    
Holy smokes. I've posted here twice and twice you were first to reply. Thanks again Wes. I'll make sure to read up on data templates.

I also found another way between the time I posted and you replied. For anyone that runs across this problem I've posted another possible solution below.

1 solution

One possible solution is adding DisplayMemberBinding attribute to GridViewColumn. The Binding Path in each DisplayMemberBinding attribute should be the same name as the property you want to map in the object. Each property also gets its own GridViewColumn.

Changed this XAML:
XML
<ListView x:Name="lvClients" HorizontalAlignment="Left" Height="300" VerticalAlignment="Top" Width="300" >
     <ListView.View>
         <GridView>
             <GridViewColumn/>
         </GridView>
     </ListView.View>
</ListView>


To this:

XML
<ListView x:Name="lvClients" HorizontalAlignment="Left" Height="300" VerticalAlignment="Top" Width="300" >
    <ListView.View>
        <GridView>
            <GridViewColumn Header="ID" DisplayMemberBinding="{Binding Path=ID}"/>
            <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=Name}"/>
        </GridView>
    </ListView.View>
</ListView>
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900