我一直在努力将项目添加到的2列中ListView。在我的Windows Forms应用程序中,我有类似以下内容:
ListView
// 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); }
然后,我会从我的班级召集这个班Form.cs。
Form.cs
如何在WPF中执行此操作?最好,我不想使用很多XAML。
如果您ListView在XAML中定义:
<ListView x:Name="listView"/>
然后,您可以添加列并在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" }); }
请参阅MyItem下面的定义。
MyItem
但是,在XAML中定义列会更容易(在ListView定义内):
<ListView x:Name="listView"> <ListView.View> <GridView> <GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/> <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/> </GridView> </ListView.View> </ListView>
然后只需在C#中填充列表:
public Window() { // Initialize this.InitializeComponent(); // Populate list this.listView.Items.Add(new MyItem { Id = 1, Name = "David" }); }
MyItem 定义如下:
public class MyItem { public int Id { get; set; } public string Name { get; set; } }