繁体   English   中英

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

[英]How to add rows to WPF grid in MVVM

这是我的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 ));

只需将更多Record添加到itemsource集合中即可。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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