Alright, I've been scratching my head over this one for the better part of the day, Google has been of little help, my fellow project mates have not been able to solve it either and we're less than a day away from our deadline. Help us Obi-One Stackoverflow, you're our only hope:
I have a DataGrid which consists of a variable number of columns of variable types (DataGridTextColumn, DataGridComboBoxColumn, DataGridCheckBoxColumn)
and I need to bind data to them.
Each of these columns will represent a database-query which is the reason for the grid having to be very flexible. What I need help with is how to bind and add data to these columns in the code-behind part.
EDIT It seems I forgot to make this clear: some columns will contain data of the same type (in our instance: "Grade"). Depending on the subtype of this object we will need a different type for the column. As such, the Grid will have n columns, some of which have to be bound to data of the same type.
END EDIT
I cannot design a container-class which has one Property for each column since they change dynamically, From what I've read I cannot bind the columns to different indices of an array, and the last approach-idea I had is to bind the different columns to a string representing the type of the data ("checkbox", "string", "combobox") and then simply add a container which has a property with that name to each individual column. I couldn't find a way to do this since there doesn't seem to be an "Add" method to invoke on the grid's columns! To summarize in wishful-thinking-code what I need is something looking like this:
//Create an arbitrary number of columns
for(int i = 0; i < NR_CHECKBOXES; ++i) {
DataGridCheckBoxColumn col = new DataGridCheckBoxColumn();
col.Header = titles[i];
//which are bound to a container with correct type of data
col.Binding = new Binding("checkboxes[" + i + "]");
grid.Columns.Add(col);
}
grid.Add(checkboxes); //and then populate the grid
or something like this:
//Create an arbitrary number of columns
for(int i = 0; i < NR_CHECKBOXES; ++i) {
DataGridCheckBoxColumn col = new DataGridCheckBoxColumn();
col.Header = titles[i];
col.Binding = new Binding("Data");
col.Add(checkboxes[i]); //Populate the column specifically
grid.Columns.Add(col);
}
where checkboxes is a list of objects that has the property 'Data' (sorry, couldn't codify this inline by pressing tab then $, probably since I'm on a Swedish keyboard). These loops would then be copied for each type of column and data I have (ComboBoxes and TextBoxes).
I hope this is enough to explain my problem, and that someone out there knows the proper way to achieve this in WPF.