【问题标题】:ListView is not updated (repainted) upon item replace using ObservableCollectionListView 在使用 ObservableCollection 替换项目时未更新(重新绘制)
【发布时间】:2015-08-04 08:49:05
【问题描述】:

我有一个简单的ViewModel,其中包含一个绑定到ItemsSource 属性的ObservableCollectionListView。在预定义的时间段内,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


【解决方案1】:

我等了很久才有人回答(我讨厌有人回答他自己的问题,但是......)。

可观察集合维护 DataObject 项的快照,并且由于 DataObject Equals 方法被重写以仅通过 ID 比较两个对象,因此无论对象内的数据发生更改,都不会触发项更改绑定。
解决方案是将 DataObject 包装到另一个提供 prop 的对象中。更改通知。然后一切都按预期工作 - 替换包装器内的快照将触发项目更改绑定

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-05
    • 1970-01-01
    • 2016-10-03
    • 2014-01-15
    • 2011-07-02
    • 2019-10-25
    • 1970-01-01
    相关资源
    最近更新 更多