2015-03-03 50 views
0

我試圖將對象列表綁定到緊湊框架上的DataGrid。這是我有:DataGrid對象的綁定列表

public class Order 
{ 
    //Other stuff 
    public Customer Customer 
    { 
     get { return _customer; } 
    } 
} 

public class Customer 
{ 
    //Other stuff 
    public string Address 
    { 
     get { return _address; } 
    } 
} 

現在我想將DataGrid綁定到訂單列表,並只顯示某些屬性(顧客的地址是其中之一):

List<Order> orders = MethodThatGetsOrders(); 
datagrid.DataSource = orders; 
datagrid.TableStyles.Clear(); 
DataGridTableStyle ts = new DataGridTableStyle(); 
ts.MappingName = orders.GetType().Name; //This works OK 
DataGridTextBoxColumn tb = new DataGridTextBoxColumn(); 
tb.MappingName = orders.GetType().GetProperty("Customer").GetType().GetProperty("Address").Name; //Throws NullRef 
ts.GridColumnStyles.Add(tb); 
datagrid.TableStyles.Add(ts); 

我怎麼能在DataGridTextBoxColumn上顯示客戶的地址?
感謝

回答

2

我將不得不惹綁定圍繞前形成一個視圖模型(或更好的轉接器),讓你可以綁定一個平面模型容易:

public class OrderViewModel 
{ 
    private Order _order; 

    public string Address 
    { 
     get { return _order.Customer.Address; } 
    } 

    // similar with other properties 

    public OrderViewModel(Order order) 
    { 
     _order = order; 
    } 
} 

要生成ViewModelList做:

List<OrderViewModel> viewModels = yourList.Select(m=> new OrderViewModel(m)).ToList(); 

而且簡單綁定:

YourGridView.Datasource = new BindingSource(viewModels, null); 
+0

參考:http://www.dofactory.com/net/adapter-design-pattern – 2015-03-03 10:45:00

+0

對於輸入的Thx,我需要爲此創建另一個類。有沒有辦法將Address屬性關聯到TextBoxColumn MappingName? – 2015-03-03 16:54:30

+1

很確定有一種方法,但是如果你編寫這個適配器,你可以自動綁定......甚至可以使用INotifyPropertyChanged的2種方法......它更容易...類只是將它的調用委託給構造函數傳入的引用所以如果這就是你所害怕的,它不會消耗太多的記憶。 – 2015-03-03 16:58:18