user589195
user589195

Reputation: 4250

Binding WPF datagrid to a List<List<object>>

I have a List of Lists of Objects List<List<object>> and im wanting to bind it to a WPF datagrid programatically.

So far I have tried:

Code

dtgCores.ItemsSource = resinSystemData.data;

xaml

<DataGrid Name="dtgCores" Grid.Column="1">

But I just get 2 columns Capacity and Count. Could someone please advise?

I have a list of the column headers I would like to use in the format of a list aswell.

Please let me know if oyu need anymore information.

Upvotes: 3

Views: 2215

Answers (2)

SilverCorvus
SilverCorvus

Reputation: 3076

By default a DataGrid will bind columns to the properties of the objects in the immediate list it receives as the ItemSource. This is why when using a List<List<object>> as 'ItemSource', each line will show the two properties of a List, Capacity and Count.

You can however create your own DataGridColumn for each column and bind them to an index of the list. Here's is an example:

public void SetTestDataInGrid(List<List<object>> testData)
{
    testGrid.Columns.Clear();
    int colCount = testData.Max(x => x.Count);
    for (int i = 0; i < colCount; i++)
    {
        var currentColumn = new DataGridTextColumn();
        currentColumn.Binding = new Binding(string.Format("[{0}]", i));
        testGrid.Columns.Add(currentColumn);
    }
    testGrid.ItemsSource = testData;
}

This method checks the maximum length of the inner lists to determine the number of columns, and then creates a DataGridTextColumn for each column, binding each to the correct index of the inner list ([0],[1], etc.) and then sets the ItemSource to the testData.

You might want to also add AutoGenerateColumns="False" to the DataGrid to prevent creation of the Capacity and Count columns.

Upvotes: 3

Henk Holterman
Henk Holterman

Reputation: 273824

A datagrid is not designed for this. It needs properties for its columns (hence Capacity and Count).

You'll need to choose:

  • use another datastructure, like List<SomeClass>
  • use another Control. A nested Listbox with 2 datatemplates will probably work.

Upvotes: 3

Related Questions