簡體   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