小编Dan*_*075的帖子

WPF ListView:更改ItemsSource不会更改ListView

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

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

_itemList = new ObservableCollection<PmemCombItem>();
_itemList.CollectionChanged += new NotifyCollectionChangedEventHandler(OnCollectionChanged);
L_PmemCombList.ItemsSource = _itemList;
Run Code Online (Sandbox Code Playgroud)

为了避免刷新完整的ListView,我将新检索的列表与当前_itemList进行简单比较,更改不相同的项目,并在必要时添加/删除项目.集合"newList"包含新创建的对象,因此替换_itemList中的项目正确地发送"刷新"通知(我可以使用OnCollectionChangedObservableCollection 的事件处理程序进行记录)

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 …
Run Code Online (Sandbox Code Playgroud)

c# wpf listview

18
推荐指数
4
解决办法
4万
查看次数

标签 统计

c# ×1

listview ×1

wpf ×1