1

I'm having a bit of trouble getting the following to work:

I'm creating an ObservableCollection like this:

ObservableCollection<OverViewItems> ocOrderData = new ObservableCollection<OverViewItems>();

The class OrderViewItems looks like this:

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

And then I populate it with some sample data (two rows in this case), like this:

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

And try to bind it to a WPF Datagrid like this:

dataGrid1.ItemsSource = ocOrderData;

And the XAML for the Datagrid looks like this:

        <DataGrid 
        AutoGenerateColumns="True" 
        Height="200" 
        HorizontalAlignment="Left" 
        Margin="23,172,0,0" 
        Name="dataGrid1" 
        VerticalAlignment="Top" 
        Width="1084" 
        />

Now, the datagrid displays the two rows ok, but there's no data, no columns, no nothing except a blank datagrid with two rows. Why is this? What do I do wrong?

Any help is appreciated. :)

4

2 回答 2

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; }
}
于 2012-11-22T11:32:38.817 回答
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};
}
于 2012-11-22T11:33:43.147 回答