Dynamic Wpf DataGrid Columns using PropertyDescriptors

added by lucidsnippets
1/20/2012 9:09:59 AM

2 Kicks, 1104 Views

WPF DataGrid control used in combination with custom ObervableCollection<dynamic> implementing ITypedList and providing PropertyDescriptors which enables adding columns dynamically at runtime. Columns definitions are also strongly typed and advanced column data generation can be provided by lambda delegates.


1/20/2012 9:08:54 AM
Interesting solution, would it be possible to take it a step further and support attributes?

1/20/2012 9:23:13 AM
You mean attributes for "virtual" properties? If you mena those, they are supported in DynamicPropertyDescriptor - you just pass them in one of the overloads.

1/20/2012 9:28:22 AM
I actually meant something along the lines of:
public class user
[DynamicPropertyDescriptor("First Name")]
public string FirstName { get; set; }

Similar to how you would use the description attribute in a winforms propertygrid

1/20/2012 9:37:12 AM
Well, if you only need a name, you could just use public class user { [DisplayName("First Name")] public string FirstName { get; set; } } and initialize DynamicDataGridSource without any propertydescriptors. Default ones would be picked up, and display name used in DynamicDataGrid column generation. So it's actually even easier and you could get rid of quite some code presented, including the proxies, you would only need to keep a class deriving from ObservableCollection implementing ITypedList and columns display name logic override from DynamicDataGrid

If you look at the code DisplayNameAttribute is already used when we initialize DynamicPropertyDescriptor. But DynamicPropertyDescriptor has much more power than just a custom column header name.