我正在尝试在自定义 ListView
中实现搜索功能因此我隐藏了Items
自定义 ObservableCollection
这允许 AddRange
,类似于 one defined on damonpayne.com (对于那里的 tl;dr-ers,基本上它会抑制触发 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
重新填充.
除一个小但重要的警告外,这工作正常并且符合预期:
问题是 ListViewItem
s' Group
并非始终从 this.Items
携带至 base.Items
因此,所有项目都出现在“默认”组中。
关于为什么会发生这种情况以及如何解决它有什么想法吗?
更新
我仍然坚持这一点。当然在做 .ToArray()
只是创建了 Items
的浅拷贝所以 Group
应该保留吗?
Maverik已证实这一点:
更新2
好的,经过更多调查后,我发现了问题所在。
添加ListViewItem
时s 到 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 - 解决方案
最佳答案
背景
想通了!
我不知道为什么,但没有在应该抛出的时候抛出异常。
异常 无法在多个位置添加或插入项“item0”。
应该被抛出。
(在从 .designer.cs
中清除了一些东西后,它被抛出(虽然奇怪的是当单步执行时没有...)
根据要求,从包含自定义 ListView
的表单设计器中清除的代码是
this.ListView.Items.AddRange(new System.Windows.Forms.ListViewItem[] {
listViewItem1,
listViewItem2,
listViewItem3,
listViewItem4,
listViewItem5,
listViewItem6});
这些只是我之前为测试添加的一些临时项目,但设计师一定出于某种原因记住了它们。)
解决方案
解决方案如this SO answer所述我的代码现在是:
this.BeginUpdate();
base.Items.Clear();
base.Items.AddRange(this.Items.Select((ListViewItem)a => a.Clone()).ToArray());
this.EndUpdate();
关于c# - ListViewItem 的组未通过另一个集合保留,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12476858/