At run time I want to dynamically build grid columns (or another display layout) in a WPF ListView. I do not know the number and names of the columns before hand.
I want to be able to do:
MyListView.ItemSource = MyDataset;
MyListView.CreateColumns();
i’d try following approach:
A) you need to have the list box display grid view – i believe this you’ve done already
B) define a style for GridViewColumnHeader:
in my case, i had a whole bunch of other properties set, but in the basic scenario – you’d need Loaded event. Clicked – this is useful if you want to add sorting and filtering functionality.
C) in your listview code, bind the template with your gridview:
D) then in you OnHeaderLoaded handler, you can set a proper template based on the column’s data
//select and apply your data template here.
E) I guess you’d need also to acquire ownership of ItemsSource dependency property and handle it’s changed event.
the GridViewColumn class itself doesn’t have much properties, so you might want to add some information there using attached properties – i.e. like unique column tag – header most likely will be used for localization, and you will not relay on this one.
In general, this approach, even though quite complicated, will allow you to easily extend your list view functionality.