将ObservableCollection绑定到wpf数据网格:网格保持为空

Wal*_*oni 6 c# data-binding wpf datagrid observablecollection

我想绑定ObservableCollection到wpf datagrid.我ObservableCollection不是空的,但是,我的数据网格保持空白:

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

    public Fenetre_EvtCode()
    {
        InitializeComponent();

        EvtCode myEvt = new EvtCode();
        glb_ObservableEvtCode   =   myEvt.GetAllEvtCode();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的xaml:

<DataGrid Foreground="Aqua" 
          Name="myDataGridEvtCode" 
          AutoGenerateColumns="True"  
          HorizontalAlignment="Stretch" 
          Margin="0,0,0,0" 
          VerticalAlignment="Stretch" 
          Height="453" 
          ItemsSource="{Binding glb_ObservableEvtCode}" />
Run Code Online (Sandbox Code Playgroud)

我再说一遍:我看了调试,我ObservableCollection不是空的.

有谁知道为什么ma datagrid保持空?

Ste*_*uer 16

您需要绑定到公共属性.

public ObservableCollection<EvtCode> ObservableEvtCode
{
  get
  {
    return this.glb_ObservableEvtCode;
  }
}
Run Code Online (Sandbox Code Playgroud)

和XAML:

<DataGrid  
    ... 
    DataContext="{Binding RelativeSource={RelativeSource AncestorType=Window}}"
    ItemsSource="{Binding ObservableEvtCode}" >
</DataGrid>
Run Code Online (Sandbox Code Playgroud)

编辑:也参见这个答案