开发者

Add a new row to DataGrid at runtime (WPF)

I have a DataGrid and fill it when window loaded, like this:

private void Window_Loaded(object sender, RoutedEventArgs e) {
    var list = DbService.GetStuffsFull();
    dataGrid.ItemsSourc开发者_运维技巧e = list;
}

and when i try to add a new row at run-time by this code:

Stuff item = new Stuff();
dataGrid.Items.Add(item);

I get this error:

Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.

how can I add a new row at runtime?


You cannot modify items in Items collection if you provided it as ItemsSource. You should either add item to your list (with INotifyCollectionChanged implemented or you should initially populated Items property via Add method.

The error description is pretty clear, isn't it?


try doing something like this: var row = dataGrid.NewRow();

    dataGrid.Rows.Add(row);
    row["column1"] = "data1";  
    row["column2"] = "data2";
    row["column3"] = "data3";

InitializeComponent();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜