我将一个WPF DataGrid绑定到一个可观察的集合。
在Xaml中
<DataGrid x:Name="DGSnapshot"
ItemsSource="{Binding Source=Snapshot}"
Grid.Row="1"
Margin="20,45,20,-46"
AutoGenerateColumns="True">
</DataGrid>这在网格中增加了8行,即“快照”一词中字母的确切数量。但是,没有来自“可选集合”的数据。当我调试程序时,它显示了DGSnapshot.ItemsSource=“快照”
但是如果我在代码中输入这个
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; }
}发布于 2018-09-20 12:36:25
不能绑定到公共字段。只能绑定到属性。
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}"https://stackoverflow.com/questions/52425245
复制相似问题