编辑:对不起,我不再有下面提到的代码。这是一个巧妙的解决方案,虽然很复杂。
我发布了一个示例项目,描述了如何使用 PropertyDescriptor 和 lambda 委托与动态 ObservableCollection 和 DynamicObject 来填充具有强类型列定义的网格。
可以在运行时动态地添加/删除列。如果您的数据不是已知类型的对象,您可以创建一个数据结构,允许任意数量的列进行访问,并为每个“列”指定一个 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)
如果是一些真实的物体,甚至更好
public class User
{
public string FirstName { get; set; }
public string LastName{ get; set; }
...
}
您可以指定强类型的列(与您的数据模型相关):
var propertyDescriptors = new List<PropertyDescriptor>
{
new DynamicPropertyDescriptor<User, string>("First name", x => x.FirstName ),
new DynamicPropertyDescriptor<User, string>("Last name", x => x.LastName ),
...
}
var users = retrieve some users
Users = new DynamicDataGridSource<User>(users, propertyDescriptors, PropertyChangedListeningMode.Handler);
然后,您只需绑定到用户集合,并在您指定它们时自动生成列。传递给属性描述符的字符串是列标题的名称。在运行时,您可以向“用户”添加更多 PropertyDescriptor,向网格添加另一列。