AutoColumn WPF DataGrid Generation via ICustomTypeDescriptor

In a test project, I was able to auto-generate the columns of DataGrid WPF in the following scenario, where the data is stored in a dictionary, and the binding is done through PropertyDescriptors:

public class People:List<Person>{ ... } public class Person:Dictionary<string,string>,INotifyPropertyChanged,ICustomTypeDescriptor { } 

The problem I am facing in my real life project is I am using MVVM, so it is a PeopleViewModel that inherits ViewModelBase and therefore cannot inherit List <Person>. I tried to implement an IList <Person> instead with an internal <Person> list and explicitly setting the DataContext to an IList <Person> link, but that didn't work.

I saw a similar publication on WinGridView forms binding here , so I wonder if the same logic is applied in WPF, and first of all, which exactly causes the implementation of ICustomTypeDescriptor when inheriting List <T> which is missing when you just implement IList <T> instead .

+6
c # wpf
source share
2 answers

DataGrid uses CollectionView for your collection to create properties. More specifically, it drops CollectionView into IItemProperties , which CollectionView not implemented by default. If you do not implement IList (NOT generic) then the default value of CollectionView will be used.

So, the implementation of this non-standard IList interface should solve this problem ( List<T> implements both, so it works if you exit List<Person> ).

+6
source share

Since it was not already mentioned, I had a related problem when the columns in the DataGrid were not automatically generated when there were no rows; it turns out that the DataGrid did not consider my IItemProperties implementation at IItemProperties (I don’t know why), but used exclusively the ICustomTypeDescriptor implementation for each individual row object to create columns, which works but results in no columns if there are no rows.

The solution was to implement ITypedList (I left the implementation of IItemProperties , just in case) in the collection type. Now I get the columns correctly created for me in whether there are rows.

+1
source share

All Articles