C# 将项目添加到 WPF ListView 中的列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15865829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add Items to Columns in a WPF ListView
提问by davidweitzenfeld
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:
我一直在努力将项目添加到ListView
. 在我的 Windows 窗体应用程序中,我有这样的事情:
// 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
.
然后我会从我的Form.cs
.
How can I do this in WPF? Preferably, I wouldn't like to use a lot of XAML.
我怎样才能在 WPF 中做到这一点?最好,我不想使用大量的 XAML。
采纳答案by Phil
Solution With Less XAML and More C#
使用更少 XAML 和更多 C# 的解决方案
If you define the ListView
in XAML:
如果您ListView
在 XAML 中定义:
<ListView x:Name="listView"/>
Then you can add columns and populate it in C#:
然后你可以添加列并在 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.
见MyItem
下面的定义。
Solution With More XAML and less C#
使用更多 XAML 和更少 C# 的解决方案
However, it's easier to define the columns in XAML (inside the ListView
definition):
但是,在 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>
And then just populate the list in C#:
然后在 C# 中填充列表:
public Window()
{
// Initialize
this.InitializeComponent();
// Populate list
this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}
See definition of MyItem
below.
见MyItem
下面的定义。
MyItem
Definition
MyItem
定义
MyItem
is defined like this:
MyItem
定义如下:
public class MyItem
{
public int Id { get; set; }
public string Name { get; set; }
}