我使用此代码对列表视图控件中的项进行排序,但它只是在详细视图中工作,对于其他视图没有任何反应。我错过了什么吗? 注意:FileListItem是一个继承自ListViewItem的类。
public class ListViewItemComparer : IComparer
{
private SortOrder sortOrderAcDe;
private SortBy sortByProperty;
//
public ListViewItemComparer(SortOrder sortOrder, SortBy sortBy)
{
sortOrderAcDe = sortOrder;
sortByProperty = sortBy;
}
//
public int Compare(object x, object y)
{
FileListItem itemX = (FileListItem)x;
FileListItem itemY = (FileListItem)y;
int result = 0;
//x is directory , y is file
if (itemX.IsDirectory && !itemY.IsDirectory)
{
return -1;
}
//x is file , y is directory
if (!itemX.IsDirectory && itemY.IsDirectory)
{
return 1;
}
//both are directories
if (itemX.IsDirectory)
{
switch (sortByProperty)
{
case SortBy.Name:
result = String.Compare(itemX.Name, itemY.Name, false);
break;
case SortBy.Size:
result = String.Compare(itemX.Name, itemY.Name, false);
break;
}//switch
}//if
//both are files
if (!itemX.IsDirectory)
{
switch (sortByProperty)
{
case SortBy.Name:
result = String.Compare(itemX.Name, itemY.Name, false);
break;
case SortBy.Size:
result = CompareLong(itemX.Size, itemY.Size);
break;
}//switch
}//if
//ifDescending
if (sortOrderAcDe == SortOrder.Descending)
{
result = -result;
}
//return
return result;
}
//
private int CompareLong(long x, long y)
{
if (x < y)
return -1;
if (x > y)
return 1;
return 0;
}
}
然后我用这段代码来调用
public void SortItems(SortOrder sortOrder, SortBy sortBy)
{
this.ListViewItemSorter = new ListViewItemComparer(sortOrder, sortBy);
}