c# – WPF ListView:更改ItemsSource不会更改ListView

我正在使用ListView控件来显示一些数据.有一个后台任务接收列表内容的外部更新.新收到的数据可能包含较少,更多或相同数量的项目,并且项目本身可能已更改.

ListView.ItemsSource绑定到OberservableCollection(_itemList),以便在ListView中也可以看到_itemList的更改.

_itemList = new ObservableCollection<PmemCombItem>();
_itemList.CollectionChanged += new NotifyCollectionChangedEventHandler(OnCollectionChanged);
L_PmemCombList.ItemsSource = _itemList;

为了避免刷新完整的ListView,我将新检索的列表与当前的_itemList进行简单比较,更改不一致的项目,如有必要,添加/删除项目.集合“newList”包含新创建的对象,所以替换_itemList中的一个项目正确地发送一个“刷新”通知(我可以使用ObservableCollection的事件处理程序OnCollectionChanged来记录)

Action action = () =>
{
    for (int i = 0; i < newList.Count; i++)
    {
        // item exists in old list -> replace if changed
        if (i < _itemList.Count)
        {
            if (!_itemList[i].SameDataAs(newList[i]))
                _itemList[i] = newList[i];
        }
        // new list contains more items -> add items
        else
            _itemList.Add(newList[i]);
     }
     // new list contains less items -> remove items
     for (int i = _itemList.Count - 1; i >= newList.Count; i--)
         _itemList.RemoveAt(i);
 };
 dispatcher.BeginInvoke(dispatcherPriority.Background,action);

我的问题是,如果在这个循环中有很多项目被更改,ListView不会刷新,并且屏幕上的数据保持原样,而且我不明白.

即使是这样一个更简单的版本(交换所有元素)

List<PmemCombItem> newList = new List<PmemCombItem>();
foreach (PmemViewItem comb in combList)
    newList.Add(new PmemCombItem(comb));

if (_itemList.Count == newList.Count)
    for (int i = 0; i < newList.Count; i++)
        _itemList[i] = newList[i];
else
{
    _itemList.Clear();
    foreach (PmemCombItem item in newList)
        _itemList.Add(item);
}

不能正常工作

有什么线索吗?

UPDATE

如果在更新所有元素后手动调用以下代码,一切都可以正常工作

OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));

但这当然会导致UI更新我还想避免的一切.

解决方法

这是我必须做的,让它上班.
MyListView.ItemsSource = null;
MyListView.ItemsSource = MyDataSource;

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...