简体   繁体   English

将WPF数据网格绑定到List <List <object >>

[英]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. 我有一个列表的对象List<List<object>> ,我想以编程方式将其绑定到WPF数据网格。

So far I have tried: 到目前为止,我尝试过:

Code

dtgCores.ItemsSource = resinSystemData.data;

xaml XAML

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

But I just get 2 columns Capacity and Count. 但我只获得2列容量和计数。 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. 如果oyu需要更多信息,请告诉我。

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> 使用另一个数据结构,如List<SomeClass>
  • use another Control. 使用另一个控件。 A nested Listbox with 2 datatemplates will probably work. 具有2个datatemplates的嵌套列表框可能会起作用。

By default a DataGrid will bind columns to the properties of the objects in the immediate list it receives as the ItemSource . 默认情况下, DataGrid会将列绑定到它作为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 . 这就是为什么当使用List<List<object>>作为'ItemSource'时,每一行将显示ListCapacityCount的两个属性。

You can however create your own DataGridColumn for each column and bind them to an index of the list. 但是,您可以为每个列创建自己的DataGridColumn ,并将它们绑定到列表的索引。 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 . 此方法检查内部列表的最大长度以确定列数,然后为每列创建DataGridTextColumn ,将每个列绑定到内部列表的正确索引( [0][1]等),然后将ItemSource设置为testData

You might want to also add AutoGenerateColumns="False" to the DataGrid to prevent creation of the Capacity and Count columns. 您可能还想将AutoGenerateColumns="False"添加到DataGrid以防止创建CapacityCount列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM