将 WPF DataGrid 绑定到 ObservableCollection

Binding a WPFDataGrid to ObservableCollection

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

在Xaml我有

<DataGrid x:Name="DGSnapshot"
              ItemsSource="{Binding Source=Snapshot}"
              Grid.Row="1"
              Margin="20,45,20,-46"
              AutoGenerateColumns="True">
</DataGrid>

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

但是如果我在代码中输入这个

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

然后绑定工作。当我调试时 DGGrid.ItemsSource 显示数据列表。

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

跟需要有关系吗

<Windows.Resources Something here/>

在Xaml代码中?

我已经阅读了以下帖子,但仍然无法理解

Bind an ObservableCollection to a wpf datagrid : Grid stays empty

How to bind WPF DataGrid to ObservableCollection

我的完整 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; }
}

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

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