如何在MVVM中将行添加到WPF网格中



这是我的Mainwindow.cs代码

        Property p = new Property(RandomColumnName(),RandomColumnValues());
        records.Add(new Record(p ));
        ColumnCollection = new ObservableCollection<DataGridColumn>();
        foreach (var column in columns) // creates grid with the specified columns
        {
            var binding = new Binding(string.Format("Properties[{0}].Value", column.Index));
            ColumnCollection.Add(new DataGridTextColumn() { Header = column.Name, Binding = binding });
        }

在我的XAML 中

       <StackPanel Margin="10,4,0,0">
            <DataGrid
             x:Name="dataGrid"
             cust:DataGridColumnsBehavior.BindableColumns="{Binding ColumnCollection}"
                AutoGenerateColumns="False"
             ItemsSource="{Binding Path=records}"/>
        </StackPanel>
public class Property:INotifyPropertyChanged
{
    public string Name { get; set; }
    public object Value { get; set; }
    public Property(string name,object value)
    {
        this.Name = name;
        this.Value = value;
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

  public class Record
{
    private 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; }
    }

}

现在它只向列中添加一行。

如何添加多行??

感谢

为什么要添加多行,只添加了一项:

Property p = new Property(RandomColumnName(),RandomColumnValues());
records.Add(new Record(p ));

只需向itemsource集合中添加更多的Record即可。

最新更新