我设法使仅使用这样的一行代码就可以动态添加列:
MyItemsCollection.AddPropertyDescriptor(
new DynamicPropertyDescriptor<User, int>("Age", x => x.Age));
关于这个问题,这不是一个基于 XAML 的解决方案(因为如上所述没有合理的方法来做到这一点),它也不是一个可以直接使用 DataGrid.Columns 操作的解决方案。它实际上与 DataGrid 绑定的 ItemsSource 一起操作,它实现了 ITypedList 并因此为 PropertyDescriptor 检索提供了自定义方法。在代码中的一处,您可以为网格定义“数据行”和“数据列”。
如果你有:
IList<string> ColumnNames { get; set; }
//dict.key is column name, dict.value is value
Dictionary<string, string> Rows { get; set; }
你可以使用例如:
var descriptors= new List<PropertyDescriptor>();
//retrieve column name from preprepared list or retrieve from one of the items in dictionary
foreach(var columnName in ColumnNames)
descriptors.Add(new DynamicPropertyDescriptor<Dictionary, string>(ColumnName, x => x[columnName]))
MyItemsCollection = new DynamicDataGridSource(Rows, descriptors)
并且使用绑定到 MyItemsCollection 的网格将填充相应的列。这些列可以在运行时动态修改(新添加或现有删除),网格将自动刷新它的列集合。
上面提到的 DynamicPropertyDescriptor 只是对常规 PropertyDescriptor 的升级,并提供了带有一些附加选项的强类型列定义。否则,DynamicDataGridSource 将与基本 PropertyDescriptor 一起正常工作。