6

I would like to bind an ObservableCollection to wpf datagrid. My ObservableCollection is not empty, but, my datagrid stay empty :

public partial class Fenetre_EvtCode : Window
{
    ObservableCollection<EvtCode> glb_ObservableEvtCode;

    public Fenetre_EvtCode()
    {
        InitializeComponent();

        EvtCode myEvt = new EvtCode();
        glb_ObservableEvtCode   =   myEvt.GetAllEvtCode();
    }
}

Here is my xaml:

<DataGrid Foreground="Aqua" 
          Name="myDataGridEvtCode" 
          AutoGenerateColumns="True"  
          HorizontalAlignment="Stretch" 
          Margin="0,0,0,0" 
          VerticalAlignment="Stretch" 
          Height="453" 
          ItemsSource="{Binding glb_ObservableEvtCode}" />

I repeat : I looked in debug, and my ObservableCollection is not empty.

Anyone know why ma datagrid stay empty?

Yael
  • 1,566
  • 3
  • 18
  • 25
Walter Fabio Simoni
  • 5,671
  • 15
  • 55
  • 80
  • 2
    Where do you set your `DataContext`? Also, I don't believe you can bind to fields - I think you have to bind to a property, although I could be wrong. – Daniel Kelley Feb 26 '13 at 10:51
  • 1
    Implement INotifyPropertyChanged on your Window and call this after `glb_ObservableEvtCode = myEvt.GetAllEvtCode();` that line – Jordy van Eijk Feb 26 '13 at 10:53
  • 1
    @JordyVanEI I think this is not needed in this special case since the collection is created in the constructor of the window – Stephan Bauer Feb 26 '13 at 10:57

2 Answers2

16

You need to bind to a public property.

public ObservableCollection<EvtCode> ObservableEvtCode
{
  get
  {
    return this.glb_ObservableEvtCode;
  }
}

And XAML:

<DataGrid  
    ... 
    DataContext="{Binding RelativeSource={RelativeSource AncestorType=Window}}"
    ItemsSource="{Binding ObservableEvtCode}" >
</DataGrid>

Edit: see also this answer

Community
  • 1
  • 1
Stephan Bauer
  • 9,120
  • 5
  • 36
  • 58
  • 1
    What is the underlying reason due to which it does not work only by setting ItemsSource property on datagrid? if we have defined an observable collection (already populated) in the code behind and setting the ItemSource property in datagrid then WPF run time should be able to bind to it using MVVM pattern. I wonder why it doesn't. – RBT Jun 08 '16 at 01:34
0

My case, if this can help anyone:

The data members of Class should also be public property.

Hari Chaudhary
  • 630
  • 1
  • 7
  • 20