2009-01-13 75 views
2

有沒有辦法將對象的子屬性綁定到datagridview?這裏是我的代碼:將子屬性綁定到DataGridView

public class Person 
{ 
    private string id; 
    private string name; 
    private Address homeAddr; 
    public string ID 
    { 
     get { return id; } 
     set { id = value; } 
    } 
    public string Name 
    { 
     get { return name; } 
     set { name = value; } 
    } 
    public Address HomeAddr 
    { 
     get { return homeAddr; } 
     set { homeAddr = value; } 
    } 
} 

public class Address 
{ 
    private string cityname; 
    private string postcode; 
    public string CityName 
    { 
     get { return cityname; } 
     set { cityname = value; } 
    } 
    public string PostCode 
    { 
     get { return postcode; } 
     set { postcode = value; } 
    } 
} 

而且,當Person類型的對象綁定到datagridview時,我想顯示ID,Name,CityName。請注意,CityName是HomeAddr的一個屬性。

+0

你想CITYNAME和郵編在一列或兩個單獨的列? – BFree 2009-01-13 02:58:21

+0

當然是兩列。 – Graviton 2009-01-13 03:15:43

回答

0

如果你有DataGridView AutoGenerateColumns = true,真的沒有簡單的方法來做到這一點。您最好的選擇是提前設置DataGridView,然後手動填充DataGridView。

或者,您可以實施ITypedList,但如果您問我,那會有點痛苦。

0

BLToolkit有BLToolkit.ComponentModel.ObjectBinder

這些特點是:

Support for field binding along with property binding. 

Support for inner class field and property binding such as Order.Address.Line1. 

Support for the ObjectView feature which is available by assigning an object view type to the ObjectBinder.ObjectViewType property. An object view is an object that implements the IObjectView interface. This interface includes only one property - object Object { get; set; }. An object view can implement additional properties based on the assosiated object. The ObjectBinder will combine all of these properties with main object properties and create a single PropertyDescriptor collection. This feature can be used to separate UI presentation logic from business model objects and to keep them clean. ObjectView should be a stateless, lightweight object as its single instance can be assigned to many assosiated objects. 

The ObjectBinder is optimized for high performance applications such real-time multithreaded message processing and distribution banking systems. So it does not use reflection to access objects. The standard way (which is used by the BindingSource) is to call the TypeDescriptor.GetProperties method to get a PropertyDescriptor collection. This method creates property descriptors that access object properties by reflection. The ObjectBinder has its own mechanism to avoid unnessasy reflection and boxing/unboxing operations.