I have a grid, and I’m setting the DataSource to a List<IListItem>. What I want is to have the list bind to the underlying type, and disply those properties, rather than the properties defined in IListItem. So:
public interface IListItem
{
string Id;
string Name;
}
public class User : IListItem
{
string Id { get; set; };
string Name { get; set; };
string UserSpecificField { get; set; };
}
public class Location : IListItem
{
string Id { get; set; };
string Name { get; set; };
string LocationSpecificField { get; set; };
}
How do I bind to a grid so that if my List<IListItem> contains users I will see the user-specific field? Edit: Note that any given list I want to bind to the Datagrid will be comprised of a single underlying type.
Data-binding to lists follows the following strategy:
IListSource? if so, goto 2 with the result ofGetList()IList? if not, throw an error; list expectedITypedList? if so use this for metadata (exit)public Foo this[int index](for someFoo)? if so, usetypeof(Foo)for metadatalist[0]) for metadataList<IListItem>falls into “4” above, since it has a typed indexer of typeIListItem– and so it will get the metadata viaTypeDescriptor.GetProperties(typeof(IListItem)).So now, you have three options:
TypeDescriptionProviderthat returns the properties forIListItem– I’m not sure this is feasible since you can’t possibly know what the concrete type is given justIListItemList<User>etc) – simply as a simple way of getting anIListwith a non-object indexerITypedListwrapper (lots of work)ArrayList(i.e. no public non-object indexer) – very hacky!My preference is for using the correct type of
List<>… here’s anAutoCastmethod that does this for you without having to know the types (with sample usage);Note that this only works for homogeneous data (i.e. all the objects are the same), and it requires at least one object in the list to infer the type…