Click here to Skip to main content
14,669,324 members
Rate this:
Please Sign up or sign in to vote.
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)
<ListView x:Name="lvClients" HorizontalAlignment="Left" Height="300" VerticalAlignment="Top" Width="300" >
     <ListView.View>
         <GridView>
             <GridViewColumn/>
         </GridView>
     </ListView.View>
</ListView>


(Code behind)
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)
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

Rate this:
Please Sign up or sign in to vote.

Solution 1

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:
<ListView x:Name="lvClients" HorizontalAlignment="Left" Height="300" VerticalAlignment="Top" Width="300" >
     <ListView.View>
         <GridView>
             <GridViewColumn/>
         </GridView>
     </ListView.View>
</ListView>


To this:

<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>
   
v2

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100