实际上,实现起来相对简单,前提是您愿意忍受 P/Invoke 的苦差事来访问内置于本机 Windows 控件中但不由 .NET FW 公开的功能。
我演示在我的回答中 https://stackoverflow.com/questions/4826556/treeview-remove-checkbox-by-some-nodes/4826740#4826740如何使用 TreeView 控件完成完全相同的操作,并且考虑到 ListView 与 TreeView 的相似程度,因此可以使用 ListView 以几乎相同的方式完成此操作并不特别令人惊讶。
这是所需的所有代码(确保您已添加Imports
声明为System.Runtime.InteropServices
命名空间):
' P/Invoke declarations
Private Const LVIF_STATE As Integer = &H8
Private Const LVIS_STATEIMAGEMASK As Integer = &HF000
Private Const LVM_FIRST As Integer = &H1000
Private Const LVM_SETITEM As Integer = LVM_FIRST + 76
<StructLayout(LayoutKind.Sequential, Pack:=8, CharSet:=CharSet.Auto)> _
Private Structure LVITEM
Public mask As Integer
Public iItem As Integer
Public iSubItem As Integer
Public state As Integer
Public stateMask As Integer
<MarshalAs(UnmanagedType.LPTStr)> _
Public lpszText As String
Public cchTextMax As Integer
Public iImage As Integer
Public lParam As IntPtr
End Structure
<DllImport("user32.dll", CharSet:=CharSet.Auto)> _
Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As Integer, ByVal wParam As IntPtr, ByRef lParam As LVITEM) As IntPtr
End Function
''' <summary>
''' Hides the checkbox for the specified item in a ListView control.
''' </summary>
Private Sub HideCheckBox(ByVal lvw As ListView, ByVal item As ListViewItem)
Dim lvi As LVITEM = New LVITEM()
lvi.iItem = item.Index
lvi.mask = LVIF_STATE
lvi.stateMask = LVIS_STATEIMAGEMASK
lvi.state = 0
SendMessage(lvw.Handle, LVM_SETITEM, IntPtr.Zero, lvi)
End Sub
然后你可以像这样简单地调用上面的方法:
Private Sub btnHideCheckForSelected_Click(ByVal sender As Object, ByVal e As EventArgs)
' Hide the checkbox next to the currently selected ListViewItem
HideCheckBox(myListView, myListView.SelectedItems(0))
End Sub
生成看起来有点像这样的东西(在单击番茄和黄瓜项目的“隐藏检查”按钮后):
![Sample ListView, with checkboxes removed from individual items](https://i.stack.imgur.com/DBSnO.png)