简体   繁体   English

将对象列表绑定到DataGrid

[英]Binding List of Object to DataGrid

I'm trying to bind a list of objects to a DataGrid on the compact framework. 我正在尝试将对象列表绑定到紧凑型框架上的DataGrid。 This is what I have: 这就是我所拥有的:

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

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

Now I want to bind the DataGrid to a list of Order and display only certain properties (the customer's address is one of them): 现在,我想将DataGrid绑定到Order列表并仅显示某些属性(客户的地址是其中之一):

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);

How can I display the customer's address on the DataGridTextBoxColumn? 如何在DataGridTextBoxColumn上显示客户的地址?
Thanks 谢谢

I would form a viewmodel (or better an adapter) before having to mess around with bindings and get a flat model you can bind easily to: 在不得不弄乱绑定并获得可以轻松绑定到的平面模型之前,我将先形成一个viewmodel(或更好的适配器)。

public class OrderViewModel
{
    private Order _order;

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

    // similar with other properties

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

To generate the ViewModelList do: 要生成ViewModelList,请执行以下操作:

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

And to bind simply: 并简单地绑定:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM