WPF & ListView - Adding Columns and Items @ Runtime
Please excuse my noobiness.
I've come over from Windows Forms so I can use the awesome Fluent Ribbon Control Suite. And I am redoing an app for someone.
Basically, I need to be able to programmatically create new Column
s and populate them with Items from a DB Query at runtime. And depending on which button was clicked, I will also need to Clear all items in the ListView and repopulate it with different Column names along with new items from another DB Query.
But I'm having a hard time trying to figure this out. I just don't get it. The first thing I did, before looking online, was this (thinking and hoping it would be very similar to how Windows Forms does it):
GridViewColumn gvc = new GridViewColumn();
gvc.Header = "hi baeltazor!";
listView1.Items.Add(gvc);
But, I was wrong. What I tried to do there was create a column called "hi baeltazor!" and add it to the ListView. How can we populate a ListView with items and columns at runtime?
The only solutions I've seen have 开发者_如何学运维alot of XAML involved, and I don't get how that works, because I can't change XAML at runtime?
<ListView x:Name="ListViewControl">
<ListView.View>
<GridView x:Name="GridViewControl"/>
</ListView.View>
</ListView>
and in code behind,
ListViewControl.ItemsSource = ItemsSourceObject; //your query result
GridViewColumn column = new GridViewColumn();
column.Header = "Name";
column.DisplayMemberBinding = new Binding("Name");
GridViewControl.Columns.Add(column);
One advice... think about using DataGrid control (seems apt for your requirement) It can auto generate columns for the items source. If you really want to create columns on your own... you can do that by using 4 types of DataGridColumn s which may not need CellTemplate to be set (this is easy to achieve from code behind). and of course there is a type in which you can specify the CellTemplate
精彩评论