【问题标题】:Binding a WPFDataGrid to ObservableCollection将 WPFDataGrid 绑定到 ObservableCollection
【发布时间】:2025-12-29 02:20:15
【问题描述】:

我将 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

Binding DatagridColumn to StaticResource pointing to ObservableCollection in WPF

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

【问题讨论】:

    标签: wpf binding datagrid itemssource


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的回答,但它仍然不适用于此更改。
    • @GrantMcConville 抱歉,我忘了解决另一个问题。查看我的编辑。
    • 这非常有效。您可以将 DataContext 设置为 Xaml 中的 MainWindow 吗?我试过了,但出现了堆栈溢出。
    • 非常感谢您的帮助
    • @GrantMcConville 如果您想在 XAML 中将 DataContext 绑定到您自己,请将此属性放在 Window 元素中:DataContext="{Binding RelativeSource={RelativeSource Self}} 但是,通常在 WPF 应用程序中,您有一个要绑定的 ViewModel 类到而不是背后的代码。