Add Items to Columns in a WPF ListView

2019-01-03 16:24发布

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.

1条回答
够拽才男人
2楼-- · 2019-01-03 17:14

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; }
}
查看更多
登录 后发表回答