0

我偶然发现了以下问题:我正在使用实时过滤 ListView 中的项目的答案在 LargeIcon 视图中创建过滤后的项目列表。我为列表视图定义了组:

//  Define the Groups within the listview.                
foreach (CategoryObject category in JManager.jfo.categories)
{
   ListViewGroup lvg = new ListViewGroup();
   lvg.Header = lvg.Name = category.name;
   channellistView.Groups.Add(lvg);
}

我使用以下代码将项目迭代地添加到列表视图和主列表中:

            lvi.Group = channellistView.Groups[CategoryName];
            lvi.Tag = Obj;
            channellistView.Items.Add(lvi);

            ListViewItem mlvi = lvi.Clone() as ListViewItem;
            mlvi.Group = channellistView.Groups[CategoryName];
            masterChannelList.Add(mlvi);

这是当我在“过滤器”文本框中键入字母时处理过滤的代码:

channellistView.BeginUpdate();

channellistView.Items.Clear();
// This filters and adds your filtered items to listView
foreach (ListViewItem item in masterChannelList.Where(lvi => 
         lvi.Text.ToLower().StartsWith(searchmetroTextBox.Text.ToLower().Trim())))
            {
                channellistView.Items.Add(item);
            }

channellistView.EndUpdate();

在我键入字符串的第二个字母后出现问题。看来该行:

channellistView.Items.Clear();

以某种方式更改主列表中的组集合。我知道这一点是因为我在上面的行上设置了一个断点并显示特定项目的主列表组。执行上述行后,项目的组设置为空。这导致列表现在显示一个“默认”分组,其中包含其组被取消的项目。

我的理解是,有问题的行不应该以任何方式修改 Group 集合。

4

1 回答 1

0

通过更多的调试,我能够解决这个问题。我注意到 Group 属性还有一个“Items”集合,用于跟踪分配给该组的项目。在调试过程中,我注意到项目倾向于重复。这使我检查了用于分配项目的代码。这就是我发现问题的地方。

在将它们添加到主列表时,我没有创建项目的新实例。我正在使用每个项目的副本。因此,我将该代码更改为:

            ListViewItem mlvi = new ListViewItem();
            mlvi.Text = Obj.title;
            mlvi.ImageIndex = 1;
            mlvi.Group = channellistView.Groups[CategoryName];
            mlvi.Tag = Obj;
            masterChannelList.Add(mlvi);

此外,我需要将过滤结果的代码更改为:

        // This filters and adds your filtered items to listView
        foreach (ListViewItem item in masterChannelList.Where(lvi => lvi.Text.ToLower().StartsWith(searchmetroTextBox.Text.ToLower().Trim())))
        {
            ListViewItem filteredItem = new ListViewItem();
            filteredItem.Text = item.Text;
            filteredItem.Group = item.Group;
            filteredItem.ImageIndex = item.ImageIndex;
            channellistView.Items.Add(filteredItem);
        }

新代码确保我获得了列表视图项的新实例,而不是副本。

于 2021-11-27T15:32:14.010 回答