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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15087131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:00:31  来源:igfitidea点击:

Bind an ObservableCollection to a wpf datagrid : Grid stays empty

c#wpfdata-bindingdatagridobservablecollection

提问by Walter Fabio Simoni

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

我想将一个绑定ObservableCollection到 wpf 数据网格。我ObservableCollection的不是空的,但是,我的数据网格保持空:

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:

这是我的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 ObservableCollectionis not empty.

我再说一遍:我在调试中查看过,我ObservableCollection的不是空的。

Anyone know why ma datagrid stay empty?

任何人都知道为什么 ma datagrid 保持为空?

采纳答案by Stephan Bauer

You need to bind to a public property.

您需要绑定到公共属性

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

And XAML:

和 XAML:

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

Edit:see also this answer

编辑:另请参阅此答案

回答by Hari Chaudhary

My case, if this can help anyone:

我的情况,如果这可以帮助任何人:

The data members of Class should also be public property.

Class 的数据成员也应该是公共属性。