在运行时向 DataGrid 添加新行 (WPF)
我有一个 DataGrid 并在加载窗口时填充它,如下所示:
private void Window_Loaded(object sender, RoutedEventArgs e) {
var list = DbService.GetStuffsFull();
dataGrid.ItemsSource = list;
}
当我尝试通过此代码在运行时添加新行时:
Stuff item = new Stuff();
dataGrid.Items.Add(item);
我收到此错误:
操作无效,同时 ItemsSource 正在使用中。访问和 修改元素 相反,ItemsControl.ItemsSource。
如何在运行时添加新行?
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.ItemsSource = 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您将
Items
集合中的项目提供为ItemsSource
,则无法修改该集合中的项目。您应该将项目添加到您的list
(已实现INotifyCollectionChanged
),或者您应该首先通过Add
方法填充Items
属性 ?错误描述很清楚,不是吗
You cannot modify items in
Items
collection if you provided it asItemsSource
. You should either add item to yourlist
(withINotifyCollectionChanged
implemented or you should initially populatedItems
property viaAdd
method.The error description is pretty clear, isn't it?
尝试做这样的事情:
var row = dataGrid.NewRow();
try doing something like this:
var row = dataGrid.NewRow();