【发布时间】:2012-09-10 16:59:44
【问题描述】:
我正在尝试在自定义ListView 中实现搜索功能,因此我使用自定义ObservableCollection 隐藏Items,它允许AddRange,类似于one defined on damonpayne.com(用于tl;那里的博士基本上是在添加多个项目时抑制触发OnCollectionChanged事件,然后使用NotifyCollectionChangedAction.Reset触发):
public new MyCollection<ListViewItem> Items { get; protected set; }
MyCollection_CollectionChanged() 填充 base.Items:
this.BeginUpdate();
base.Items.Clear();
base.Items.AddRange(this.Items.ToArray());
this.EndUpdate();
这个想法是,当项目不满足搜索条件时,它们会从base.Items(即System.Windows.Forms.ListView)中删除,但仍保留在this.Items(即My.Name.Space.MyListView)。当搜索被取消或条款改变时,base.Items 可以被this.Items 重新填充。
除了一个小但重要的警告之外,这可以正常工作并且符合预期:
问题是ListViewItems'Group 没有始终如一地从this.Items 传送到base.Items,因此所有项目都出现在“默认”组中。
关于为什么会发生这种情况以及如何解决它的任何想法?
更新
我仍然坚持这一点。当然,.ToArray() 只是创建了Items 的浅表副本,所以应该保留Group?
这已经被Maverik证实了:
更新 2
好的,经过更多调查后,我发现它发生在哪里。
将ListViewItems 添加到MyCollection<ListViewItem> 时:
var item0 = new ListViewItem();
var item0.Group = this.Groups["foo"];
//here this.Items.Count = 0
this.Items.Add(item0);
//here this.Items.Count = 1 with item0 having group "foo"
var item1 = new ListViewItem();
var item1.Group = this.Groups["bar"];
//here this.Items.Count = 1 with item0 having group "foo"
this.Items.Add(item1);
//here this.Items.Count = 2 with item0 having group "null" and item1 having group "bar"
我还检查了将 MyCollection< 替换为正常的 ObservableCollection< 的情况,但仍然会发生同样的情况。
更新 3 - 解决方案
【问题讨论】:
-
啊哈,tl;dr-ers 部分 +1
标签: c# winforms listview .net-3.5