【发布时间】: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