为什么在更改 ItemsSource 时 DataGrid 不更新? [英] Why does the DataGrid not update when the ItemsSource is changed?
问题描述
我的 wpf 应用程序中有一个数据网格,但有一个简单的问题.我有一个通用列表,每次将对象添加到集合时,我都想将此集合绑定到我的数据网格数据源.而且我对使用 observable 集合不感兴趣.
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.
这是代码:
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();
}
有什么想法吗?
推荐答案
ItemsSource
始终相同,引用您的集合,没有变化,没有更新.你之前可以把它清零:
The ItemsSource
is always the same, a reference to your collection, no change, no update. You could null it out before:
dgOrderDetail.ItemsSource = null;
dgOrderDetail.ItemsSource = OrderDetailObjects;
或者,您也可以只刷新项目:
Alternatively you could also just refresh the Items:
dgOrderDetail.ItemsSource = OrderDetailObjects; //Preferably do this somewhere else, not in the add method.
dgOrderDetail.Items.Refresh();
我不认为你真的想在那里调用 UpdateLayout
...
I do not think you actually want to call UpdateLayout
there...
(拒绝使用 ObservableCollection 并不是一个好主意)
这篇关于为什么在更改 ItemsSource 时 DataGrid 不更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!