使用 ObservableCollection 替换项目后,ListView 不会更新(重新绘制)
ListView is not updated (repainted) upon item replace using ObservableCollection
我有一个简单的 ViewModel
,其中包含一个绑定到 ItemsSource
属性的 ObservableCollection
。的 ListView
。在预定义的时间段内,ViewModel
将收到更新(快照)- 具有相同 ID 但不同值的新 DataObject
。我现在正在做的是:
- find the index of the item with this id
- if there is no such item: add it to the collection
- if there is - replace it: obsColItems[index] = newDataObject;
我希望 ListView
反映更改,但只有添加操作可见 - 后续更改(替换项目)不可见。我连接了一个 CollectionChange
事件并且它被正确触发但 ListView
仍然显示初始数据。
我试过的几件事:
1. remove and then insert the item at the appropriate index - that
leaved me with a bad taste in the mouth (it also messed the current
selected item).
2. After bit of research `BindingList` was mentioned in few similar SO questions
and it did the trick - the `ListView` is now updating, but it seams to
be full of functionality I don't relay need.
ObservableCollection
和项目替换有问题吗?如何让 ListView
在项目替换后更新?
我等了很长时间有人回答(我讨厌有人回答他自己的问题但是......)。
可观察集合维护 DataObject 项目的快照,并且由于 DataObject Equals 方法被重写以仅通过 ID 比较两个对象,因此无论对象内的数据发生变化,项目更改绑定都不会被触发。
解决方案是将 DataObject 包装到另一个提供 prop 的对象中。更改通知。然后一切都按预期工作 - 替换包装器内的快照将触发项目更改绑定
我有一个简单的 ViewModel
,其中包含一个绑定到 ItemsSource
属性的 ObservableCollection
。的 ListView
。在预定义的时间段内,ViewModel
将收到更新(快照)- 具有相同 ID 但不同值的新 DataObject
。我现在正在做的是:
- find the index of the item with this id
- if there is no such item: add it to the collection
- if there is - replace it: obsColItems[index] = newDataObject;
我希望 ListView
反映更改,但只有添加操作可见 - 后续更改(替换项目)不可见。我连接了一个 CollectionChange
事件并且它被正确触发但 ListView
仍然显示初始数据。
我试过的几件事:
1. remove and then insert the item at the appropriate index - that
leaved me with a bad taste in the mouth (it also messed the current
selected item).
2. After bit of research `BindingList` was mentioned in few similar SO questions
and it did the trick - the `ListView` is now updating, but it seams to
be full of functionality I don't relay need.
ObservableCollection
和项目替换有问题吗?如何让 ListView
在项目替换后更新?
我等了很长时间有人回答(我讨厌有人回答他自己的问题但是......)。
可观察集合维护 DataObject 项目的快照,并且由于 DataObject Equals 方法被重写以仅通过 ID 比较两个对象,因此无论对象内的数据发生变化,项目更改绑定都不会被触发。
解决方案是将 DataObject 包装到另一个提供 prop 的对象中。更改通知。然后一切都按预期工作 - 替换包装器内的快照将触发项目更改绑定