本文共 3223 字,大约阅读时间需要 10 分钟。
List Control and List View
For convenience, MFCencapsulates the list control in two ways. You canuse list controls:
CListView makes it easy to integrate a listcontrol with the MFC document/view architecture, encapsulating the control muchas encapsulatesan edit control: the control fills the entire surface area of an MFC view. (The view is the control, cast to CListView.)
A CListView object inherits from andits base classes and adds a member function to retrieve the underlying listcontrol. Use view members to work with the view as a view. Usethe memberfunction to gain access to the list control's member functions. Use thesemembers to:
To obtain a reference to the CListCtrl underlying a CListView, call GetListCtrl fromyour list view class:
C++
CListCtrl& listCtrl = GetListCtrl();
This topic describes both ways to use the listcontrol.
源文档 <>
使用CListCtrl
To use CListCtrl directly in a dialog box
源文档 <>
注意列表控件属性View选择Report.
添加列
在初始化列表视图时,先要调用InsertColumn()插入各个列
CRectrect;
m_contacts.GetClientRect(&rect);
m_contacts.InsertColumn(0,_T("姓名"), LVCFMT_LEFT, rect.Width() * 3 / 5);
m_contacts.InsertColumn(1,_T("电话"), LVCFMT_LEFT, rect.Width() *5);
添加项
表项插入与删除,通过InsertItem插入行,通过SetItemText设置行各列项
CStringdata[2] = { _T("张三"), _T("1234") };
LV_ITEMlvi;
lvi.mask= LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM;
lvi.iSubItem= 0;
lvi.pszText= data[0].GetBuffer(0);
lvi.iImage= 0;
lvi.iItem= 0;
intnRow = m_contacts.InsertItem(&lvi);
for(int i = 0; i<2; i++) m_contacts.SetItemText(nRow, i, data[i]);
排序
列表控件属性sort选择升序或降序
自定义参数
自定义参数,通过SetItemData设置,通过GetItemData取得
处理鼠标双击事件消息
选中列表控件,在属性视图的控件事件列表中选择NM_DBLCLK,点击下拉按钮选择add.
在生成的消息处理函数中添加如下代码
voidCFirstPage::OnNMDblclkListContacts(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMITEMACTIVATEpNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);
CDialogAddContactdlg;
intnIndex =pNMItemActivate->iItem;
dlg.m_strName= m_contacts.GetItemText(nIndex, 0);
dlg.m_strPhone= m_contacts.GetItemText(nIndex, 1);
TRACE(_T("修改%d联系人.姓名:%s,电话:%s"),nIndex, dlg.m_strName, dlg.m_strPhone);
INT_PTRnResponse = dlg.DoModal();
if(nResponse == IDOK)
{
CStringstrName = dlg.m_strName;
CStringstrPhone = dlg.m_strPhone;
if(!strName.IsEmpty() && !strPhone.IsEmpty())
{
//删除再添加
m_contacts.DeleteItem(nIndex);
LV_ITEMlvi;
lvi.mask= LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM;
lvi.iSubItem= 0;
lvi.pszText= strName.GetBuffer(0);
lvi.iImage= 0;
lvi.iItem= 0;
intnRow = m_contacts.InsertItem(&lvi);
m_contacts.SetItemText(nRow,0, strName);
m_contacts.SetItemText(nRow,1,strPhone);
}
}
elseif (nResponse == IDCANCEL)
{
}
*pResult= 0;
}