【问题标题】:How to sort the selection, when i sort the underlying list, of a ListView in virtual mode?当我在虚拟模式下对 ListView 的基础列表进行排序时,如何对选择进行排序?
【发布时间】:2015-04-14 21:36:33
【问题描述】:
当ListView 处于虚拟模式 时,当它通过OnRetrieveItem 事件询问时,您负责将与索引n 对应的ListView 提供给ListItem。
我根据自己的规则对列表进行排序,并告诉列表视图重新绘制:
listView1.Invalidate();
这很好,花花公子。
除非用户选择了某些项目。现在当树重绘时,不同的项被选中。
对SelectedIndices进行排序的技术是什么?
但如果我对自己的个人列表进行排序
【问题讨论】:
标签:
winforms
listview
virtualmode
【解决方案1】:
您需要存储选定的对象、排序、按新索引查找对象并重新选择它们。
代码可能看起来像这样(根据需要进行优化):
void listView1_ColumnClick( object sender, ColumnClickEventArgs args )
{
// Store the selected objects
List<MyDataObject> selectedObjects = new List<MyDataObject>();
foreach ( int index in listView1.SelectedIndices )
{
selectedObjects.Add( m_MyDataObjectsColl[index] );
}
// Clear all selected indices
listView1.SelectedIndices.Clear();
// Sort the list
SortListView(listView1, args);
// Reselect the objects according to their new indices
foreach ( MyDataObject selectedObject in selectedObjects )
{
int index = m_MyDataObjectsColl.FindIndex(
delegate( MyDataObject obj ) { return obj == selectedObject; }
);
listView1.SelectedIndices.Add( index );
}
}