CMFCListCtrl是MFC Feature Pack中提供的新类,它很好的封装了CListCtrl的排序功能,
只要重写比较函数就OK了。
virtual int OnCompareItems(LPARAM lParam1, LPARAM lParam2, int iColumn);
但是,在使用GroupView模式时,以上的比较函数仍然被调用,但并没有排序。
AFX_INLINE int CListCtrl::EnableGroupView(BOOL fEnable)
{
ASSERT(::IsWindow(m_hWnd));
return (int)ListView_EnableGroupView(m_hWnd, fEnable); // LVM_ENABLEGROUPVIEW
}
面对以上问题,对CMFCListCtrl派生出CGroupSortableListCtrl类,以实现组内排序。
以下附上代码:

#pragma once
// CGroupSortableListCtrl
class CGroupSortableListCtrl : public CMFCListCtrl
{
DECLARE_DYNAMIC(CGroupSortableListCtrl)
public:
CGroupSortableListCtrl();
virtual ~CGroupSortableListCtrl();
protected:
DECLARE_MESSAGE_MAP()
protected:
static int CALLBACK CompareGroupProc(int iGroupId1, int iGroupId2, void* lParamSort);
public:
virtual void Sort(int iColumn, BOOL bAscending = TRUE , BOOL bAdd = FALSE);
virtual int OnCompareGroups(int iGroupId1, int iGroupId2, int iColumn);
};
// CGroupSortableListCtrl
IMPLEMENT_DYNAMIC(CGroupSortableListCtrl, CMFCListCtrl)
CGroupSortableListCtrl::CGroupSortableListCtrl()
{
}
CGroupSortableListCtrl::~CGroupSortableListCtrl()
{
}
BEGIN_MESSAGE_MAP(CGroupSortableListCtrl, CMFCListCtrl)
END_MESSAGE_MAP()
void CGroupSortableListCtrl::Sort(int iColumn, BOOL bAscending/* = TRUE*/, BOOL bAdd/* = FALSE*/)
{
CWaitCursor wait;
GetHeaderCtrl().SetSortColumn(iColumn, bAscending, bAdd);
m_iSortedColumn = iColumn;
m_bAscending = bAscending;
if (IsGroupViewEnabled())
{
ListView_SortGroups(m_hWnd, CompareGroupProc, this);
}
SortItems(CompareProc, (LPARAM)this);
}
int CGroupSortableListCtrl::CompareGroupProc(int iGroupId1, int iGroupId2, void* lParamSort)
{
CGroupSortableListCtrl* pList = (CGroupSortableListCtrl*)lParamSort;
ASSERT_VALID(pList);
int nRes = pList->OnCompareGroups(iGroupId1, iGroupId2, pList->m_iSortedColumn);
nRes = pList->m_bAscending ? nRes : -nRes;
return nRes;
}
int CGroupSortableListCtrl::OnCompareGroups(int /*iGroupId1*/, int /*iGroupId2*/, int /*iColumn*/)
{
return 0;
}