简体   繁体   中英

How to add rows to WPF grid in MVVM

This is my Mainwindow.cs code

        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 });

        }

and in my 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; }
    }


}

Now it add's only one row to the columns.

How can I add multiple rows ??

Thanks

why should it add more than one row, there's only one item added:

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

just add more Record s to the itemsource collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM