65.9K
CodeProject 正在变化。 阅读更多。
Home

动态显示或隐藏列表控件列的有效方法

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.68/5 (13投票s)

2005年6月9日

CPOL

1分钟阅读

viewsIcon

127025

downloadIcon

1724

一篇关于如何动态隐藏列表控件列的文章。

CListCtrlEx Demo

引言

最近,在我的一个项目中,我需要一个派生自 CListCtrl 的类,该类具有动态显示/隐藏其列的能力。 使用 CListCtrl::DeleteColumn() 不是一个好主意,因为在这种情况下,子项目的索引会不断变化,因此评估子项目会变得非常复杂。 我在互联网上搜索,没有找到现有的解决方案。 最后,我不得不编写自己的类 - CListCtrlEx 来实现此功能。

CListCtrlEx 的主要功能

  • 动态隐藏/显示列。
  • 提供内置上下文菜单以选择列,并且它是根据您插入的列动态创建的。
  • 拖放重新排序列(您必须启用 LVS_EX_HEADERDRAGDROP 样式)。
  • 自动在注册表中保存/恢复列的顺序、宽度和可见性。
  • 您不需要更改现有的 CListCtrl 派生类的代码。 您所要做的就是将它们的基类更改为 CListCtrlEx

使用 CListCtrlEx 类

  1. 将以下文件添加到您的项目中
    • HeaderCtrlEx.h
    • HeaderCtrlEx.cpp
    • ListCtrlEx.h
    • ListCtrlEx.cpp
  2. 将以下两个光标文件导入到您的资源中,并根据方括号中提到的 ID 更改它们
    • res\VE_SPLIT.CUR [IDC_HEADER_OPEN]
    • res\VE_SIZEB.CUR [IDC_HEADER_SIZE]
  3. CListCtrlEx 派生您自己的类,例如 CMyListCtrl
  4. 在资源编辑器中将一个列表控件添加到您的对话框中,并将其绑定到一个成员变量,例如 m_wndList。 当然,该变量应该是 CMyListCtrl 对象。
    void CTestListCtrlDlg::DoDataExchange(CDataExchange* pDX)
    {
        CDialog::DoDataExchange(pDX);
        DDX_Control(pDX, IDC_LIST, m_wndList);
    }
  5. 保存/恢复列的状态。
    BOOL CTestListCtrlDlg::OnInitDialog()
    {
        CDialog::OnInitDialog();
    
        // Enable column drag & drop
        m_wndList.SetExtendedStyle(m_wndList.GetExtendedStyle() 
                                      | LVS_EX_HEADERDRAGDROP);
    
        // Insert columns and items to the list control here
    
        // Set the sub registry key to store the columns' state
        m_wndList.SetRegistryKey("MyListCtrl");
    
        // Restore the state of the columns
        m_wndList.RestoreState();
    }
    
    void CTestListCtrlDlg::OnDestroy()
    {
        CDialog::OnDestroy();
    
        // TODO: Add your message handler code here
    
        // Save the state of the columns
        m_wndList.SaveState();
    }
© . All rights reserved.