使用ObservableCollection替换项目时不会更新(重新绘制)ListView

时间:2015-08-04 08:49:06

标签: c# wpf listview viewmodel observablecollection

我有一个简单的ViewModel,其中包含与ObservableCollection道具绑定的ItemsSource。一个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更新?

1 个答案:

答案 0 :(得分:0)

我等了很长时间才回答(当有人回答他自己的问题时,我讨厌它......)。

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

相关问题