How do I bind a WPF DataGrid to a variable number of columns?

后端 未结 8 1549
逝去的感伤
逝去的感伤 2020-11-22 10:29

My WPF application generates sets of data which may have a different number of columns each time. Included in the output is a description of each column that will be used t

8条回答
  •  感动是毒
    2020-11-22 10:49

    I managed to make it possible to dynamically add a column using just a line of code like this:

    MyItemsCollection.AddPropertyDescriptor(
        new DynamicPropertyDescriptor("Age", x => x.Age));
    

    Regarding to the question, this is not a XAML-based solution (since as mentioned there is no reasonable way to do it), neither it is a solution which would operate directly with DataGrid.Columns. It actually operates with DataGrid bound ItemsSource, which implements ITypedList and as such provides custom methods for PropertyDescriptor retrieval. In one place in code you can define "data rows" and "data columns" for your grid.

    If you would have:

    IList ColumnNames { get; set; }
    //dict.key is column name, dict.value is value
    Dictionary Rows { get; set; }
    

    you could use for example:

    var descriptors= new List();
    //retrieve column name from preprepared list or retrieve from one of the items in dictionary
    foreach(var columnName in ColumnNames)
        descriptors.Add(new DynamicPropertyDescriptor(ColumnName, x => x[columnName]))
    MyItemsCollection = new DynamicDataGridSource(Rows, descriptors) 
    

    and your grid using binding to MyItemsCollection would be populated with corresponding columns. Those columns can be modified (new added or existing removed) at runtime dynamically and grid will automatically refresh it's columns collection.

    DynamicPropertyDescriptor mentioned above is just an upgrade to regular PropertyDescriptor and provides strongly-typed columns definition with some additional options. DynamicDataGridSource would otherwise work just fine event with basic PropertyDescriptor.

提交回复
热议问题