0

I have a dictionary of dictionaries I want to display in a data grid.

var data = new Dictionary<KeyTypeA, Dictionary<KeyTypeB, string>>();

The "inner" dictionaries all share the same keys of a given set of KeyTypeB's which should become the row headers.

The question is related to this SO question, but the difference is that I don't know the keys until runtime.

Community
  • 1
  • 1
Onur
  • 5,017
  • 5
  • 38
  • 54

1 Answers1

2

You can use the DataGrid and build a collection of DataGridColumn in code as follows (where ColumnCollection is an ObservableCollection<DataGridColumn>):

foreach ( string columnName in columns )
{
     ColumnCollection.Add( new DataGridTextColumn()
                           {
                               Header = columnName,
                               Binding = new Binding( String.Format( "[{0}]", columnName ) )
                           } );
}

You'll need to figure out how to get the columns collection based on you dictionaries and types.

You'll then need to bind the ColumnCollection to your DataGrid columns (see this SO answer for that).

Community
  • 1
  • 1
KornMuffin
  • 2,887
  • 3
  • 32
  • 48
  • this is roughly the solution I ended with. – Onur Aug 03 '15 at 15:01
  • Great. This has worked for me very well. You can even take it further by introducing styles, formatting ... etc. when building the columns in code. – KornMuffin Aug 03 '15 at 15:04
  • The only downside is that you need the reference to the control in the view model, which is possible but is something I'd like to avoid. – Onur Aug 03 '15 at 15:05
  • You could define your own type which holds the Header and Binding and create a converter to convert your type to DataGridTextColumns. – KornMuffin Aug 03 '15 at 15:38
  • Could you post an example how this would look like? – Onur Aug 03 '15 at 15:41
  • I have a collection of DataGridColumns in my VM so I haven't implemented a converter to do this. Basically, you'd define a class w/ various column properties and then create a ValueConverter to convert a collection of those classes to a collection of DataGridColumns. – KornMuffin Aug 05 '15 at 15:34