Skip to main content Skip to footer

Binding to Subproperties

I while ago I was asked about binding to objects that contain other objects as properties, and whether there was a way to expose those sub-properties as columns on the grid. At the time, I suggested using OwnerDraw to display the value of the sub-properties in the grid cells, using the column's UserData property to identify which sub-property to bind to. The solution worked but was far from perfect, since it did not support editing or sorting. I did some research and found a much better solution, which I think might be useful to everyone. The solution is based on a custom data source class that extends the standard BindingList to provide sorting and deep property binding. Basically, the DeepBindingList class implements the ITypedList interface and exposes not only the properties of T but also all the sub-properties. For example, if you had the following classes:


public class Customer  
{  
    public int ID { get; set; }  
    public string Name { get; set; }  
    public Address Address { get; set; }  
}  
public class Address  
{  
    public string Street { get; set; }  
    public string City { get; set; }  
    public string Country { get; set; }  
}  

Creating a BindingList and using it as a data source for a grid, you would get three columns: ID, Name, and Address. This last column would not be very useful at all unless you implemented custom TypeConverters, UIEditors, and the like (such as OwnerDraw columns ;-). But if you created a DeepBindingList, you would get all the inner properties as well: ID, Name, Address, Address.Street, Address.City, and Address.Country. All the columns would be editable and sortable as usual. The sample attached shows how the DeepBindingList works. I hope you find it useful. Download Sample

MESCIUS inc.

comments powered by Disqus