在WPF中动态绑定网格

时间:2015-02-04 10:54:39

标签: c# 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}"/>

我只能在网格中显示标题,但不能显示行..

由于

1 个答案:

答案 0 :(得分:1)

您需要将一个可观察的集合记录作为公共属性添加到您的MainWindow:

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

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