【发布时间】:2015-08-04 08:49:05
【问题描述】:
我有一个简单的ViewModel,其中包含一个绑定到ItemsSource 属性的ObservableCollection。 ListView。在预定义的时间段内,ViewModel 将收到一个更新(快照)——新的DataObject,它具有相同的 Id 但不同的值。我现在正在做的是:
- 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 在项目替换后更新?
【问题讨论】:
-
这表明 Equals 方法在这里发挥了作用 - 如果 DataObject 覆盖 Equals 以仅检查 ID(应该如此),则列表不会更新(尽管使用 Replace 状态正确触发了集合更改事件) .如果 Equals 没有被覆盖(我线性搜索项目的索引以匹配 ID)然后 ListView 按预期更新,我假设 ListView 正在检查是否真的需要重新绘制项目的单元格.在这种情况下,它应该但是 Equals 方法返回 true,因为快照具有相同的 id 并且单元格没有重新绘制。
标签: c# wpf listview viewmodel observablecollection