WPF & ListView - Adding Columns and Items @ Runtime

10,466

Solution 1

<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);

Solution 2

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

Share:
10,466
βӔḺṪẶⱫŌŔ
Author by

βӔḺṪẶⱫŌŔ

Updated on June 05, 2022

Comments

  • βӔḺṪẶⱫŌŔ
    βӔḺṪẶⱫŌŔ almost 2 years

    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 Columns 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?