为什么当 ItemsSource 更改时 DataGrid 不更新?
我的 wpf 应用程序中有一个数据网格,我有一个简单的问题。我有一个通用列表,每次将对象添加到集合中时,我想将此集合绑定到我的数据网格数据源。我对使用可观察集合不感兴趣。
重点是我在其他地方使用相同的方法并且效果很好。但这一次,当我按下“添加”按钮时,将添加一个对象,并且数据网格会正确更新,但从添加到集合数据网格的第二个项目开始不再更新。
这是代码:
private void btnAddItem_Click(object sender, RoutedEventArgs e)
{
OrderDetailObjects.Add(new OrderDetailObject
{
Price = currentitem.Price.Value,
Quantity = int.Parse(txtQuantity.Text),
Title = currentitem.DisplayName,
TotalPrice = currentitem.Price.Value * int.Parse(txtQuantity.Text)
});
dgOrderDetail.ItemsSource = OrderDetailObjects;
dgOrderDetail.UpdateLayout();
}
有什么想法吗?
I have a datagrid in my wpf application and I have a simple problem. I have a generic list and I want to bind this collection to my datagrid data source every time an object is being added to the collection. and I'm not interested to use observable collection.
the point is I'm using the same method somewhere else and that works fine. but this time when i press Add button an object is added and datagrid updates correctly but from the second item added to collection datagrid does not update anymore.
Here is the Code :
private void btnAddItem_Click(object sender, RoutedEventArgs e)
{
OrderDetailObjects.Add(new OrderDetailObject
{
Price = currentitem.Price.Value,
Quantity = int.Parse(txtQuantity.Text),
Title = currentitem.DisplayName,
TotalPrice = currentitem.Price.Value * int.Parse(txtQuantity.Text)
});
dgOrderDetail.ItemsSource = OrderDetailObjects;
dgOrderDetail.UpdateLayout();
}
any idea ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我还发现,仅仅做
也能实现同样的行为。
I also found that just doing
would also accomplish the same behavior.
如果您使用 Lambda 将 ItemSource 绑定到过滤列表,则其不会更新。
使用 ICollectionView 解决这个问题(注释不起作用):
If you bind the ItemSource to a filtered list with for example Lambda its not updated.
Use ICollectionView to solve this problem (Comment dont work):
我使用 ObservableCollection 作为我的项目集合,而不是在视图模型中
调用 CollectionViewSource.GetDefaultView(my_collection).Refresh();
i use ObservableCollection as my items collection and than in the view model
call CollectionViewSource.GetDefaultView(my_collection).Refresh();
ItemsSource
始终相同,是对您的集合的引用,没有更改,没有更新。您可以之前将其取消:或者您也可以只刷新项目:
我认为您实际上不想在那里调用
UpdateLayout
...(拒绝使用 ObservableCollection 并不完全是一个问题)好主意)
The
ItemsSource
is always the same, a reference to your collection, no change, no update. You could null it out before:Alternatively you could also just refresh the Items:
I do not think you actually want to call
UpdateLayout
there...(Refusing to use an ObservableCollection is not quite a good idea)