我在使用以下工作时遇到了一些麻烦:
我正在创建一个像这样的ObservableCollection:
ObservableCollection<OverViewItems> ocOrderData = new ObservableCollection<OverViewItems>();
OrderViewItems类如下所示:
public class OverViewItems
{
public string OrderNo;
public int Pieces;
public string SenderName;
public string ReceiverName;
public string ReceiverAddress;
public string ReceiverZip;
public string ReceiverCity;
public DateTime DelDate;
}
然后我用一些样本数据填充它(在这种情况下是两行),如下所示:
ocOrderData.Add(new OverViewItems
{
OrderNo = "TEST",
Pieces = 1,
SenderName = "TEST SENDER",
ReceiverName = "TEST RECEIVER",
ReceiverAddress = "TEST ADDRESS",
ReceiverZip = "TEST ZIP",
ReceiverCity = "TEST CITY",
DelDate = DateTime.Now,
});
ocOrderData.Add(new OverViewItems
{
OrderNo = "TEST 2",
Pieces = 1,
SenderName = "TEST SENDER 2",
ReceiverName = "TEST RECEIVER 2",
ReceiverAddress = "TEST ADDRESS 2",
ReceiverZip = "TEST ZIP 2",
ReceiverCity = "TEST CITY 2",
DelDate = DateTime.Now,
});
并尝试将其绑定到WPF Datagrid,如下所示:
dataGrid1.ItemsSource = ocOrderData;
Datagrid的XAML如下所示:
<DataGrid
AutoGenerateColumns="True"
Height="200"
HorizontalAlignment="Left"
Margin="23,172,0,0"
Name="dataGrid1"
VerticalAlignment="Top"
Width="1084"
/>
现在,datagrid显示两行ok,但是没有数据,没有列,除了包含两行的空数据网格之外没有任何内容。为什么是这样?我做错了什么?
感谢任何帮助。 :)
答案 0 :(得分:4)
您必须使用OverViewItems
类中的属性而不是简单的公共字段
这样做应该使DataGrid正确地创建列。
public class OverViewItems
{
public string OrderNo { get; set; }
public int Pieces { get; set; }
public string SenderName { get; set; }
public string ReceiverName { get; set; }
public string ReceiverAddress { get; set; }
public string ReceiverZip { get; set; }
public string ReceiverCity { get; set; }
public DateTime DelDate { get; set; }
}
答案 1 :(得分:3)
你可以绑定到公共属性而不是字段。
public class OverViewItems
{
public string OrderNo {get;set};
public int Pieces {get;set};
public string SenderName {get;set};
public string ReceiverName {get;set};
public string ReceiverAddress {get;set};
public string ReceiverZip {get;set};
public string ReceiverCity {get;set};
public DateTime DelDate {get;set};
}