【问题标题】:Binding List of Object to DataGrid将对象列表绑定到 DataGrid
【发布时间】:2015-03-03 09:46:18
【问题描述】:

我正在尝试将对象列表绑定到紧凑框架上的 DataGrid。这就是我所拥有的:

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

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

现在我想将 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);

如何在 DataGridTextBoxColumn 上显示客户的地址?
谢谢

【问题讨论】:

    标签: c# datagrid compact-framework


    【解决方案1】:

    我会先形成一个视图模型(或更好的适配器),然后再处理绑定并获得一个可以轻松绑定到的平面模型:

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

    【讨论】:

    • 感谢输入,我需要为此创建另一个类。有没有办法将 Address 属性与 TextBoxColumn MappingName 相关联?
    • 很确定有一种方法,但是如果您编写此适配器,您可以自动绑定...甚至使用 INotifyPropertyChanged 的​​两种方式...这更容易...该类仅将其调用委托给构造函数传入的引用,因此如果您担心的话,它不会消耗太多内存。
    猜你喜欢
    • 2015-01-16
    • 2012-05-25
    • 2014-06-29
    • 2019-04-01
    • 1970-01-01
    • 2013-08-06
    • 2014-08-13
    • 2012-01-18
    • 1970-01-01
    相关资源
    最近更新 更多