在 WPF 中动态绑定网格

Dynamically bind grid in WPF

我无法查看我动态绑定到它的网格中的行这是我的代码

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        DisplayGrid();
    }

    private void DisplayGrid()
    {
        var records = new ObservableCollection<Record>();
        records.Add(new Record(new Property("FirstName", "ABC"), new Property("LastName", "DEF")));
        records.Add(new Record(new Property("FirstName", "GHI"), new Property("LastName", "JKL")));

        var columns = records.First()
            .Properties
            .Select((x, i) => new { Name = x.Name, Index = i })
            .ToArray();

        foreach (var column in columns)
        {
            var binding = new Binding(string.Format("Properties[{0}].Value", column.Index));
            dataGrid.Columns.Add(new DataGridTextColumn() { Header = column.Name, Binding = binding });
        }
    }
}

class Record
{

    readonly ObservableCollection<Property> _properties = new ObservableCollection<Property>();

    public Record(params Property[] properties)
    {
        foreach (var property in properties)
        {
            _properties.Add(property);
        }
    }

    public ObservableCollection<Property> Properties
    {
        get { return _properties; }
    }


}

在我的 XAML

       <DataGrid
        Name="dataGrid"
        AutoGenerateColumns="False"
        ItemsSource="{Binding Path=Records}"/>

我只能在我的网格中显示 headers 而不是行..

谢谢

您需要将可观察集合记录作为 public 属性 添加到主窗口:

public ObservableCollection<Record> Records {get; set;}

并使用它代替私有变量 records。还要将 DataContext = this; 添加到构造函数中。