How do I dynamically generate columns in a WPF DataGrid?

后端 未结 4 1719
一生所求
一生所求 2020-12-01 00:55

I am attempting to display the results of a query in a WPF datagrid. The ItemsSource type I am binding to is IEnumerable. As the fields returned

4条回答
  •  猫巷女王i
    2020-12-01 01:22

    my answer from Dynamic column binding in Xaml

    I've used an approach that follows the pattern of this pseudocode

    columns = New DynamicTypeColumnList()
    columns.Add(New DynamicTypeColumn("Name", GetType(String)))
    dynamicType = DynamicTypeHelper.GetDynamicType(columns)
    

    DynamicTypeHelper.GetDynamicType() generates a type with simple properties. See this post for the details on how to generate such a type

    Then to actually use the type, do something like this

    Dim rows as List(Of DynamicItem)
    Dim row As DynamicItem = CType(Activator.CreateInstance(dynamicType), DynamicItem)
    row("Name") = "Foo"
    rows.Add(row)
    dataGrid.DataContext = rows
    

提交回复
热议问题