VS2010 MFC中 使用CListCtrl的排序功能

 

   list 控件是creat的,不是拖在对话框上的。想使用CListCtrl的排序功能却犯了愁~~~

 

   还好找到方法,如下:

 

.h文件里:afx_msg void OnLvnColumnclickList1(NMHDR *pNMHDR, LRESULT *pResult);

 

.cpp文件里:

消息映射如下:

ON_NOTIFY(LVN_COLUMNCLICK,IDS_RECRODSWND, &CViewList::OnLvnColumnclickList1)

具体实现:

// 排序用的比较函数
static int CALLBACK MyCompareProc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
{
    CString &lp1 = *((CString *)lParam1);
    CString &lp2 = *((CString *)lParam2);
    int &sort = *(int *)lParamSort;
    if (sort == 0)
    {
        return lp1.CompareNoCase(lp2);
    }
    else
    {
        return lp2.CompareNoCase(lp1);
    }
}

//排序处理代码
void CViewList::OnLvnColumnclickList1(NMHDR *pNMHDR, LRESULT *pResult)
{
    //获取CMainFrame对象
    static CMainFrame* pMain = (CMainFrame *)AfxGetMainWnd();
    LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
    int Length = pMain->m_wndRecDetail.m_RecordsList.GetItemCount();
    CArray<CString,CString> ItemData;
    ItemData.SetSize(Length);
    for (int i = 0; i < Length; i++)
    {
        ItemData[i] = pMain->m_wndRecDetail.m_RecordsList.GetItemText(i,pNMLV->iSubItem);
        pMain->m_wndRecDetail.m_RecordsList.SetItemData(i,(DWORD_PTR)&ItemData[i]);  //设置排序关键字
    }
    static int sort = 0;
    static int SubItem = 0;
    if (SubItem != pNMLV->iSubItem)
    {
        sort = 0;
        SubItem = pNMLV->iSubItem;
    }
    else
    {
        if (sort == 0)
        {
            sort = 1;
        }
        else
        {
            sort = 0;
        }
    }
    pMain->m_wndRecDetail.m_RecordsList.SortItems(MyCompareProc,(DWORD_PTR)&sort);//排序
    *pResult = 0;
}

 

posted @ 2013-10-26 20:07  紫清婷  阅读(1402)  评论(0编辑  收藏  举报