我正在使用ListView
控件来显示一些数据行.有一个后台任务接收列表内容的外部更新.新接收的数据可能包含更少,更多或相同数量的项目,并且项目本身也可能已更改.
在ListView.ItemsSource
绑定到OberservableCollection
(_itemList),以便更改_itemList应在也可以看到ListView
.
_itemList = new ObservableCollection(); _itemList.CollectionChanged += new NotifyCollectionChangedEventHandler(OnCollectionChanged); L_PmemCombList.ItemsSource = _itemList;
为了避免刷新完整的ListView,我将新检索的列表与当前_itemList进行简单比较,更改不相同的项目,并在必要时添加/删除项目.集合"newList"包含新创建的对象,因此替换_itemList中的项目正确地发送"刷新"通知(我可以使用OnCollectionChanged
ObservableCollection 的事件处理程序进行记录)
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
就不会刷新,屏幕上的数据会保持原样...而这我不明白.
甚至更简单的版本(交换所有元素)
ListnewList = new List (); 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更新我仍想避免的所有内容.
更改后,您可以使用以下内容刷新Listview,这样更容易
listView.Items.Refresh();
这是我必须要做的才能让它发挥作用.
MyListView.ItemsSource = null; MyListView.ItemsSource = MyDataSource;