对象到 DataGrid 的绑定列表
Binding List of Object to 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 上显示客户的地址?
谢谢
我会先形成一个视图模型(或更好的适配器),然后再处理绑定并获得一个可以轻松绑定到的平面模型:
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);
我正在尝试将对象列表绑定到紧凑型框架上的 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 上显示客户的地址?
谢谢
我会先形成一个视图模型(或更好的适配器),然后再处理绑定并获得一个可以轻松绑定到的平面模型:
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);