简体   繁体   中英

MFC CListView custom drawing - colour row if text equals value

In my C++ MFC application I'm using a CListView in report style. I need a way to colour in a row if a value equals a specific value, ie I have a 'Validity' column, and if a value is out of range, colour the row red.

I understand that I need to use a CustomDraw handler, as custom drawing means I can make changes to the drawing context.

To add a custom draw handler, click on your List Control, go to Properties and click on Events. Add a 'NM_CUSTOMDRAW' control event handler.

This custom draw event handler colours in each row if the third column's row equals 'No':

void Test_ClientDlg::OnNMCustomdrawlistctrlvalues(NMHDR *pNMHDR, LRESULT *pResult)
{
    LPNMLVCUSTOMDRAW lpLVCustomDraw = reinterpret_cast<LPNMLVCUSTOMDRAW>(pNMHDR);
    int itemCnt = 0;
    CString text;
    RECT rc;

    switch(lpLVCustomDraw->nmcd.dwDrawStage)
    {
    case CDDS_ITEMPREPAINT:
    case CDDS_ITEMPREPAINT | CDDS_SUBITEM:
            itemCnt = listAnalysisVals->GetItemCount();
            for (int i = 0; i < itemCnt; i++)
            {
                //get each row text for 3rd column (position 2)
                text = listAnalysisVals->GetItemText(i, 2);
                if (text.Compare("No") == 0)
                {
                    if (i == (lpLVCustomDraw->nmcd.dwItemSpec))
                    {
                        lpLVCustomDraw->clrTextBk = RGB(255,50,50);
                        listAnalysisVals->GetItemRect(i,&rc,LVIR_BOUNDS);
                        listAnalysisVals->InvalidateRect(&rc, 0);
                    }
                }
            }
        break;
    default: break;
    }

    *pResult = 0;
    *pResult |= CDRF_NOTIFYPOSTPAINT;
    *pResult |= CDRF_NOTIFYITEMDRAW;
    *pResult |= CDRF_NOTIFYSUBITEMDRAW;
}

This results in:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM