tôi đang sử dụng ListView
控件来显示一些数据行。有一个后台任务接收列表内容的外部更新。新收到的数据可能包含更少、更多或相同数量的项目,而且项目本身可能已更改。
ListView.ItemsSource
绑定(bind)到 OberservableCollection
(_itemList),因此对 _itemList 的更改也应该在 ListView
中可见。
_itemList = new ObservableCollection();
_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
khác
_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 newList = 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];
khác
{
_itemList.Clear();
foreach (PmemCombItem item in newList)
_itemList.Add(item);
}
工作不正常
有什么线索吗?
gia hạn
如果我在更新所有元素后手动调用以下代码,一切正常
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
但这当然会导致 UI 更新我仍然想避免的所有内容。
改完后,可以用下面的方式刷新Listview,更简单
listView.Items.Refresh();
Tôi là một lập trình viên xuất sắc, rất giỏi!