How do I dynamically generate columns in a WPF DataGrid?

后端 未结 4 1715
一生所求
一生所求 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条回答
  •  一整个雨季
    2020-12-01 01:17

    The problem here is that the clr will create columns for the ExpandoObject itself - but there is no guarantee that a group of ExpandoObjects share the same properties between each other, no rule for the engine to know which columns need to be created.

    Perhaps something like Linq anonymous types would work better for you. I don't know what kind of a datagrid you are using, but binding should should be identical for all of them. Here is a simple example for the telerik datagrid.
    link to telerik forums

    This isn't actually truly dynamic, the types need to be known at compile time - but this is an easy way of setting something like this at runtime.

    If you truly have no idea what kind of fields you will be displaying the problem gets a little more hairy. Possible solutions are:

    • Creating a type mapping at runtime by using Reflection.Emit, I think it's possible to create a generic value converter that would accept your query results, create a new type (and maintain a cached list), and return a list of objects. Creating a new dynamic type would follow the same algorithm as you already use for creating the ExpandoObjects

      MSDN on Reflection.Emit
      An old but useful article on codeproject

    • Using Dynamic Linq - this is probably the simpler faster way to do it.
      Using Dynamic Linq
      Getting around anonymous type headaches with dynamic linq

    With dynamic linq you can create anonymous types using a string at runtime - which you can assemble from the results of your query. Example usage from the second link:

    var orders = db.Orders.Where("OrderDate > @0", DateTime.Now.AddDays(-30)).Select("new(OrderID, OrderDate)");
    

    In any case, the basic idea is to somehow set the itemgrid to a collection of objects whose shared public properties can be found by reflection.

提交回复
热议问题