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.
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
DefinitionMyItem
is defined like this:
public class MyItem
{
public int Id { get; set; }
public string Name { get; set; }
}