[英]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: 你需要选择:
List<SomeClass>
List<SomeClass>
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'时,每一行将显示List
, Capacity
和Count
的两个属性。
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
以防止创建Capacity
和Count
列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.