Friday, December 4, 2009

[WPF] How to programmatically add databound item to ListView

In this post I'll show how to programmatically add databound items to a WPF ListView - it's actually pretty straightforward but it's not the most intuitive task if you don't have a lot of experience with WPF.

Here's your xaml - pay attention to the bindings on the grid columns:

      <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=Name}"/>
      <GridViewColumn Header="Value" DisplayMemberBinding="{Binding Path=Value}"/>
We need to define a data class with Name and Value properties such as:

public class BoringData
    public string Name { get; set; }
    public string Value { get; set; }
And here comes the fun - how to programmatically add items to the ListView:

//utterly boring call to generate your data item
BoringData boredom = getBoringData(index);//<-- whatever
//add the item to the listView 
If you're thinking I post boring stuff ... well, you're right. Posts like this I mainly post so that I won't forget how it's done (and hopefully will be helpful to some other occasional WPF hacker).

No comments: