0

我有一个简单的数据结构如下:

在我的模型中

    public class Receipt
    {
    public int Id { get; set; }
    public double Price { get; set; }
    public string Store { get; set; }
    public DateTime Date { get; set; }
    }

我已经制作了其中两个对象,并试图将它们绑定到数据网格。我已经填写了两个收据的属性并将它们添加到 dataGridRows 但它们没有显示在我的 DataGrid 中。

    public MainWindow()
    {
    InitializeComponent();
    makeReceipts()
    }

    public ObservableCollection<Receipt> dataGridRows = new ObservableCollection<Receipt>();

    public Receipt receipt1 = new Receipt();
    public Receipt receipt2 = new Receipt();

    public void makeReceipts()
    {
    receipt1.Id = 1;
    receipt1.Price = 10;
    receipt1.Store = "Brugsen";
    receipt1.Date = DateTime.Today;

    receipt2.Id = 2;
    receipt2.Price = 15;
    receipt2.Store = "Netto";
    receipt2.Date = DateTime.Today;

    dataGridRows.Add(receipt1);
    dataGridRows.Add(receipt2);
    }

在我希望我的数据网格显示我拥有的收据的 MainWindow 的 xaml 中:

    <DataGrid Name="ReceiptGrid" CanUserResizeColumns="True" IsReadOnly="True" AutoGenerateColumns="True" ItemsSource="{Binding Source=dataGridRows}" />

我究竟做错了什么?

4

3 回答 3

0

认为你的问题是你必须写

ItemsSource="{Binding Path=dataGridRows}"

并不是

ItemsSource="{Binding Source=dataGridRows}"

source 是在 xaml 文件中指定另一个控件

于 2013-07-04T15:00:14.663 回答
0

首先,您可以绑定到公共属性。所以如果你想使用绑定,你至少要做:

 public ObservableCollection<Receipt> dataGridRows {get;set;}

其次,您必须执行两个步骤:

  1. 设置正确的数据上下文
  2. 设置正确的绑定表达式(路径)

假设您的网格的数据上下文是具有属性 dataGridRows 的对象,您的绑定应如下所示

 <DataGrid ItemsSource="{Binding Path=dataGridRows}" .../>
于 2013-07-04T14:17:09.997 回答
0

首先,您只能绑定公共属性,因此您需要将定义更改dataGridRows为如下所示:

public ObservableCollection<Receipt> dataGridRows { get; set; }

那么您不会将其绑定为 aSource而是绑定为 a Path,但是由于您dataGridRows已在其中定义,因此MainWindow您需要指定Source为您的,MainWindow否则它将看起来默认DataContext为您的情况未设置

<DataGrid ... ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=dataGridRows}" />

这告诉您在那里Binding寻找Window和寻找dataGridRows房产。

编辑:
通常您不会将数据放入视图中。我建议您阅读有关 MVVM 设计模式的更多信息,但基本上这个想法是您拥有 ViewModel,您将整个应用程序逻辑放入其中,不知道界面,然后在顶部您有与用户交互的视图,但在 ViewModel 中您没有t 操作控件。
您应该做的是创建具有属性的视图模型类并通过例如dataGridRows分配它。每个都有它,当您不指定源(, , )时,它将尝试在当前解决DataContextWindowFrameworkElementBingingSourceRelativeSourceElementNameBinding.PathDataContext. 如果当前控件没有指定它,那么如果将转到可视树中的父级,依此类推。

于 2013-07-04T16:02:27.700 回答