将WPFDataGrid绑定到ObservableCollection

时间:2018-09-20 12:31:11

标签: wpf binding datagrid itemssource

我将WPF DataGrid绑定到可观察的集合。

在Xaml中我有

public MainWindow()
{
    InitializeComponent();
    DGSnapshot.ItemsSource = Snapshot;
}

这将在网格中添加八行,即“快照”一词中字母的确切数量。但是,Obsevable Collection中没有数据。当我调试程序时,它显示DGSnapshot.ItemsSource =“ Snapshot”

但是如果我在代码中输入

<Windows.Resources Something here/>

然后进行绑定。当我调试时,DGGrid.ItemsSource显示数据列表。

所以我的问题是,为什么绑定在Xaml代码中不起作用,而在C#代码中?

是否与需要有关

public partial class MainWindow : Window
{
    public ObservableCollection<SnapshotRecord> Snapshot = new ObservableCollection<SnapshotRecord>()
    {
        new SnapshotRecord(){Cell1="Testing", Cell2 = "WPF", Cell3="Data", Cell4="Binding"},
        new SnapshotRecord(){Cell1="Stack", Cell2="Overflow", Cell3="is", Cell4="Awesome"}
    };

    public MainWindow()
    {
        InitializeComponent();
        DGSnapshot.ItemsSource = Snapshot;
    }
}

public class SnapshotRecord
{
    public string Cell1 { get; set; }
    public string Cell2 { get; set; }
    public string Cell3 { get; set; }
    public string Cell4 { get; set; }
}

在Xaml代码中?

我已阅读以下帖子,但仍无法弄清

Bind an ObservableCollection to a wpf datagrid : Grid stays empty

Binding DatagridColumn to StaticResource pointing to ObservableCollection in WPF

How to bind WPF DataGrid to ObservableCollection

我的完整C#代码...

with Ada.Text_IO;

procedure Main is

   package C is

      type Printer is tagged limited private;

      procedure Print
        (P : in out Printer;
         B : Integer);

   private

      type Printer is tagged limited record
         A : Integer := 0;
      end record;

   end C;

   package body C is

      procedure Print
        (P : in out Printer;
         B : Integer) is
      begin
         if B >= 0 then
            P.A := B;
         end if;
         Ada.Text_IO.Put_Line (P.A'Image);
      end Print;

   end C;

   P : C.Printer;
begin
   P.Print (-1);
end Main;

1 个答案:

答案 0 :(得分:0)

您不能绑定到公共字段。您只能绑定到属性

public ObservableCollection<SnapshotRecord> Snapshot { get; set; } = new ObservableCollection<SnapshotRecord>()
{
    new SnapshotRecord() {Cell1 = "Testing", Cell2 = "WPF", Cell3 = "Data", Cell4 = "Binding"},
    new SnapshotRecord() {Cell1 = "Stack", Cell2 = "Overflow", Cell3 = "is", Cell4 = "Awesome"}
};

此外,如果您想在开始时初始化集合,则应该重新评估数据上下文。最简单的是:

public MainWindow()
{
    InitializeComponent();
    DataContext = this;
}

另一个问题是您的XAML。您无需指定来源。更改为

 ItemsSource="{Binding Snapshot}"