开发者

WPF DataGrid AutoColumn generation via ICustomTypeDescriptor

In a test project I've managed to AutoGenerate WPF DataGrid columns in the following scenario, where the data is stored in a Dictionary and binding is performed via PropertyDescri开发者_如何转开发ptors:

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

}

The problem I'm having is in my real life project I'm using MVVM so it's PeopleViewModel which inherits ViewModelBase and hence can't inherit List<Person>. I've tried implementing IList<Person> instead with an internal List<Person> and explicitly setting the DataContext to an IList<Person> reference but that didn't work.

I've seen a similar post on binding a win forms DataGridView here, so I'm wondering if the same sort of logic applies in WPF and primarily, what exactly causes the ICustomTypeDescriptor implementation to be picked up when inheriting List<T> that is missing when you simply implement IList<T> instead.


The DataGrid uses the CollectionView for your collection to generate the properties. More specifically, it casts the CollectionView to IItemProperties, which the default CollectionView doesn't implement. If you don't implement IList (NOT the generic one), then the default CollectionView will be used.

So, implementing the non-generic IList interface should solve this (List<T> implements both, which is why it works if you derive from List<Person>).


Since it's not mentioned already, I had a related problem where the columns in the DataGrid were not being auto-generated when there were no rows; it turns out that the DataGrid wasn't looking at my IItemProperties implementation at all (I don't know why), but was using purely the ICustomTypeDescriptor implementation on each individual row object to generate the columns, which works too but results in there being no columns when there are no rows.

The solution was to implement ITypedList (I left the IItemProperties implementation too just in case) on the collection type. Now I get columns properly generated for me in whether or not there are rows.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜