0

i'm populating a datagrid programmatically but before setting the itemsource, i'm also programmatically adding the datagrid columns.

 DataGridTextColumn col = new DataGridTextColumn();
 col.Header = "MyCol";
 col.Binding = new Binding("PropertyOFObject");
 dataGrid.Columns.Add(col);

it's easy to set the binding to the properties of my object that are concrete however, as a property of this object, i have a list of another object type. now, for each instance of the second object type in that list, i'd like another column to my grid, populated with a specific property of that instance of the second object type.

how would i go about doing that in this same fashion of programmatically adding the columns and setting the bindings?

H.B.
  • 166,899
  • 29
  • 327
  • 400
ghost_mv
  • 1,170
  • 4
  • 20
  • 43
  • I have a grid. I have an object "A". A has properties, one of which is a "List" property. This list property is a list of instances of object "B". For each property, I'm programmatically adding and binding a column in my grid. I would like to do this same thing for each instance of object "B" in the list property of object "A". These columns would be added to the same grid. – ghost_mv Jun 07 '11 at 21:00

1 Answers1

1

If you want to bind the items of the child property to columns you can create a foreach loop which creates dynamic bindings, in one WPF question i gave an example for arrays this should be rather similar.

The key is to use a for-loop over the length of the list and creating property-paths with injected indexer:

new Binding("Property[" + i + "]")
Community
  • 1
  • 1
H.B.
  • 166,899
  • 29
  • 327
  • 400
  • The thing is, I'm doing a "for each" through a collection of object "A". They may or may not have any instances of object "B" in their list property. It may be empty. So I do have a "schema" of sorts that if they DO have instances in that list, the property of that instance that I always want to bind to is named "Value". I just don't have the 'source' of the binding when I'm programmatically creating it. – ghost_mv Jun 07 '11 at 21:18
  • You need to query your items for the instance which has the longest list, then you know how many columns are needed, if it matters to you that the binding in some cells will fail you should not attempt to use a quadratic structure like a datagrid for jagged data. – H.B. Jun 07 '11 at 21:21
  • I was able to use a form of your answer to get the information. I simply needed to explicitly name the path to the property's value. (i.e. new Binding("MyListProperty[" + i + "].Property");) Thx – ghost_mv Jun 07 '11 at 21:30