Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Items to Columns in a WPF ListView

I've been struggling for a while now to add items to 2 columns in a ListView. In my Windows Forms application I had a something like this:

// In my class library: public void AddItems(ListView listView) {     var item = new ListViewItem {Text = "Some Text for Column 1"};     item.SubItems.Add("Some Text for Column 2");      listView.Items.Add(item); } 

I would then call this class from my Form.cs.

How can I do this in WPF? Preferably, I wouldn't like to use a lot of XAML.

like image 667
davidweitzenfeld Avatar asked Apr 07 '13 18:04

davidweitzenfeld


1 Answers

Solution With Less XAML and More C#

If you define the ListView in XAML:

<ListView x:Name="listView"/> 

Then you can add columns and populate it in C#:

public Window() {     // Initialize     this.InitializeComponent();      // Add columns     var gridView = new GridView();     this.listView.View = gridView;     gridView.Columns.Add(new GridViewColumn {          Header = "Id", DisplayMemberBinding = new Binding("Id") });     gridView.Columns.Add(new GridViewColumn {          Header = "Name", DisplayMemberBinding = new Binding("Name") });      // Populate list     this.listView.Items.Add(new MyItem { Id = 1, Name = "David" }); } 

See definition of MyItem below.

Solution With More XAML and less C#

However, it's easier to define the columns in XAML (inside the ListView definition):

<ListView x:Name="listView">     <ListView.View>         <GridView>             <GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>             <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>         </GridView>     </ListView.View> </ListView> 

And then just populate the list in C#:

public Window() {     // Initialize     this.InitializeComponent();      // Populate list     this.listView.Items.Add(new MyItem { Id = 1, Name = "David" }); } 

See definition of MyItem below.

MyItem Definition

MyItem is defined like this:

public class MyItem {     public int Id { get; set; }      public string Name { get; set; } } 
like image 132
Phil Avatar answered Oct 12 '22 05:10

Phil