将Dictionary或ExpandoObjects绑定到DataGrid

时间:2015-03-11 10:38:28

标签: wpf vb.net dictionary wpfdatagrid

我正在尝试使用字典键作为列将List(Of Dictionary)绑定到WPF DataGrid。到目前为止,成效有限。

以下是我的尝试:

DataGrid:

    <DataGrid x:Name="DictDataGrid"  Margin="24,17,144,37" 
              AutoGenerateColumns="False"
              >
    </DataGrid>

在这里,我是如何尝试用评论

做的
    Dim DataList As New List(Of Object)
    Dim MyDict As New Dictionary(Of String, Object)

    ' Creating the first entry and adding it to list
    MyDict = New Dictionary(Of String, Object)
    MyDict.Add("Name", "New Name for this thing")
    MyDict.Add("Info", "Information about this thing")
    DataList.Add(MyDict)

    ' Creating the second entry and adding it to list
    MyDict = New Dictionary(Of String, Object)
    MyDict.Add("Name", "Next thing")
    MyDict.Add("Info", "Information about next thing")
    DataList.Add(MyDict)

    Dim tcol As New DataGridTextColumn

    ' Creating and adding a column and trying to bind it to "Name"
    tcol = New DataGridTextColumn
    tcol.Binding = New Binding("Name")
    tcol.Header = "Name"
    Me.DictDataGrid.Columns.Add(tcol)

    ' Creating and adding a column and trying to bind it to "Info"
    tcol = New DataGridTextColumn
    tcol.Binding = New Binding("Info")
    tcol.Header = "Info"
    Me.DictDataGrid.Columns.Add(tcol)

    ' Trying to assign the created list as data source for the datagrid
    Me.DictDataGrid.ItemsSource = DataList
    End Sub

有人可以帮我弄清楚出了什么问题吗?

我正在寻找的结果是这样的:
enter image description here

相反,我得到空行。

编辑:
在评论中提出建议后,我尝试使用List(Of ExpandoObject)代替List(Of Dictionary)。所以我将AutoGenerateColumns设置为True并将我的代码更改为:

    Dim TestObj As New Object
    Dim DataList As New List(Of Object)

    TestObj = New ExpandoObject()
    TestObj.Name = "This is the new name"
    TestObj.Info = "This is the new info"
    DataList.Add(TestObj)


    TestObj = New ExpandoObject()
    TestObj.Name = "Second name"
    TestObj.Info = "More info"
    DataList.Add(TestObj)

    Me.DictDataGrid.ItemsSource = DataList

仍然无效。我还需要手动添加列还是我错过了什么?

0 个答案:

没有答案