我用DrawItem()
來重畫我的CListbox
。由於某些原因,我想使用自定義比較來按我自己的規則對我的列表項進行排序,並且我使用LBS_SORT
並且沒有LBS_HASSTRING
屬性。在OnInitDialog()
中使用SetItemData()
之後,我在DrawItem()
中獲得了這些數據,但它不起作用。代碼如下圖所示:MFC CListbox GetItemData失敗
初始化代碼:
void OnInitDialog(...)
{
.........
m_List.SetListHeight (40);
for (int i = 0 ; i < 20 ; i ++) {
m_List.AddString ((const char *) i);
m_List.SetItemData (i,(100 + i));
}
....
}
比較碼:
int CompareItem(LPCOMPAREITEMSTRUCT lpCompareItemStruct)
{
ASSERT(lpCompareItemStruct->CtlType == ODT_LISTBOX);
int a = lpCompareItemStruct->itemData1;
int b = lpCompareItemStruct->itemData2;
return (a - b);
}
重繪代碼:
DrawItem (lpDIS)
{
..................
CString str;
int i = (int) GetItemData (lpDIS->itemID); // the i is not what I expect.
str.Format ("%d", (int) i);
dc.DrawText (str,CRect (&lpDIS->rcItem), DT_CENTER | DT_VCENTER | DT_SINGLELINE);
...................
}
當我使用
***index = m_List.addstring ((const char *) i) ;
m_List.setitemdata (index,(100 + i));***
它的工作原理,但如果我用一個結構來addstring,該指數是不正確的,代碼如下所示:
struct test {
int a,b,c,d;
};
init_code :
test *ptest = new test[20]; /* just a test ,we don't delete memory till application ends */
for (int i = 0 ; i < 20 ; i ++) {
ptest [i].a = i;
int index = m_List.AddString ((const char *) (ptest + i));
m_List.SetItemDataPtr (index,(void *) (100 + i));
}
compare code :
int ListEx::CompareItem(LPCOMPAREITEMSTRUCT lpCompareItemStruct)
{
// TODO: Add your code to determine the sorting order of the specified items
// return -1 = item 1 sorts before item 2
// return 0 = item 1 and item 2 sort the same
// return 1 = item 1 sorts after item 2
// ASSERT(lpCompareItemStruct->CtlType == ODT_LISTBOX);
test *pa,*pb;
pa = (test *) lpCompareItemStruct->itemData1; // crashed here
pb = (test *) lpCompareItemStruct->itemData2;
// ASSERT (pa);
// ASSERT (pb);
return (pa->a - pb->a);
}
draw_item code :
CString str;
test *ptest = (test *) (lpDIS->itemData);
str.Format ("%d", (int) ptest->a);
dc.DrawText (str,CRect (&lpDIS->rcItem), DT_CENTER | DT_VCENTER | DT_SINGLELINE);
是addstring能只使用字符串? 如果項目是一個結構數據,我怎麼能設置這些結構數據到列表框項???
這意味着我我們getitemdata()是不是我想要的。 –