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

向 ListView 控件添加组折叠行为

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.65/5 (23投票s)

2008 年 11 月 27 日

CPOL
viewsIcon

215601

downloadIcon

7792

在 Windows Vista 下向 ListView 控件添加组折叠行为

引言

ListView 控件是 WinForm 环境中一个重要但复杂的控件。 组行为被添加到此控件中,但不幸的是,我们无法折叠或展开组。

我将演示如何使用一些简单的代码在 ListView 控件上添加折叠/展开行为。

这是在 Windows Vista 和 Windows Server 2008 上的示例图像

lvnormal.jpg

默认组,没有折叠/展开行为

lvgroup.jpg

具有折叠/展开行为的组

Using the Code

  • 定义 ListView 结构体 包装器

    [StructLayout(LayoutKind.Sequential)] 
    public struct LVGROUP 
    { 
            public int cbSize; 
            public int mask; 
            [MarshalAs(UnmanagedType.LPTStr)] 
            public string pszHeader; 
            public int cchHeader; 
            [MarshalAs(UnmanagedType.LPTStr)] 
            public string pszFooter; 
            public int cchFooter; 
            public int iGroupId; 
            public int stateMask; 
            public int state; 
            public int uAlign; 
    } 
  • 定义 ENUM 数据

    public enum GroupState 
    { 
            COLLAPSIBLE = 8, 
            COLLAPSED = 1, 
            EXPANDED = 0 
    } 
  • 用于 SendMessage 函数的 Interop

    [DllImport("user32.dll")] 
    static extern int SendMessage
    	(IntPtr window, int message, int wParam, IntPtr lParam);
  • 内核方法,用于在 ListView 组上设置折叠/展开行为

    private void SetGroupCollapse(GroupState state)
    {
            for (int i = 0; i <= aoc.Groups.Count; i++){
                    LVGROUP group = new LVGROUP();
                    group.cbSize = Marshal.SizeOf(group);
                    group.state = (int)state; // LVGS_COLLAPSIBLE 
                    group.mask = 4; // LVGF_STATE 
                    group.iGroupId = i;
                    IntPtr ip = IntPtr.Zero;
                    try{
                            ip = Marshal.AllocHGlobal(group.cbSize);
                            Marshal.StructureToPtr(group, ip, true);
                            SendMessage(aoc.Handle, 0x1000 + 147, i, ip); // #define
                            LVM_SETGROUPINFO (LVM_FIRST + 147) 
                    }
                    catch (Exception ex){
                            System.Diagnostics.Trace.WriteLine
    			(ex.Message + Environment.NewLine + ex.StackTrace);
                    }
                    finally{
                            if (null != ip) Marshal.FreeHGlobal(ip);
                    }
           }
    } 

关注点

#define LVM_SETGROUPINFO (LVM_FIRST + 147)
#define ListView_SetGroupInfo(hwnd, iGroupId, pgrp) \
SNDMSG((hwnd), LVM_SETGROUPINFO, (WPARAM)(iGroupId), (LPARAM)(pgrp)) 

以上是来自 SDK 文件 commctrl.h 的定义。

限制

  • 在当前版本中,最右侧的折叠/展开图标不起作用。: (
  • 折叠/展开行为仅存在于 Windows Vista 和 Win2k8 系统中。

历史

  • 2008 年 11 月 27 日:初始发布
© . All rights reserved.