c# - ListViewItem 的组未通过另一个集合保留

标签 c# winforms listview .net-3.5

我正在尝试在自定义 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已证实这一点:

I just called in Linqpad, and while the list reference is different, you're right.. object references are same.

更新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 - 解决方案

see my answer .

最佳答案

背景

想通了!

我不知道为什么,但没有在应该抛出的时候抛出异常。

异常 无法在多个位置添加或插入项“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/

相关文章:

c# - 将字节数组转换为字符串时得到 'System.OutOfMemoryException'

c# - 从谷歌发送电子邮件在生产服务器上失败但在本地主机上工作正常

c# - Online MySqlDatabase 到 DataTable 的数据不完整

c# - 是否有 ReSharper 和 Code Contracts 都可以使用的通用 PureAttribute?

android - ListView:动态更改 sibling 的数据

c# - 动态填充数据网格

c# - 如何在 Windows 窗体应用程序设置中记录窗口位置

c# - 数据类型 text 和 varchar 在等于运算符中不兼容

c# - 在 C# 中从 ListView 中删除项目

qt - QML ListElement 传递字符串列表