Search code examples
wpfbindingdatagriditemssource

Binding a WPFDataGrid to ObservableCollection


I am binding a WPF DataGrid to an observable collection.

In Xaml I have

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

This adds eight lines to the grid, the exact number of letters in the word Snapshot. However there is no data from the Obsevable Collection. When I debug the program it shows that DGSnapshot.ItemsSource="Snapshot"

But if I type this in the code

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

Then the binding works. When I debug then DGGrid.ItemsSource shows a list of data.

So my question is why is the binding not working in the Xaml code, but it is in the C# code?

Has it got something to do with needing

<Windows.Resources Something here/>

In the Xaml code?

I have read the following posts, but still can't figure it out

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

My full C# code...

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

Solution

  • You cannot bind to a public field. You can only bind to a property.

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

    Also if you want to initialize your collection at start time you should reevaluate your datacontext. The easiest is:

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

    Another issue is your XAML. You don't need to specify the source. Change it to

     ItemsSource="{Binding Snapshot}"