我有一个列表'Name','Expected','Total'的ListView,我想在最后添加另一个列'Recount'。只有当“预期”值大于“总计”值时,“重新计数”列才会有一个复选框。
到目前为止,我已经获得了包含列的ListView,并且可以在左侧添加一个复选框,但该复选框不在列标题下(尽管我可能会在其中放置另一个没有值的列来解决这是所有的记录。
任何人都有什么想法我还能做什么?
答案 0 :(得分:7)
这实际上相对简单,只要您愿意忍受P / Invoke的苦差事来访问本机Windows控件中内置的功能,但.NET FW不会公开。
我演示in my answer here如何使用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
制作看起来有点像这样的东西(点击番茄和黄瓜项目的“隐藏检查”按钮后):
答案 1 :(得分:4)
下面的C#版本。
private void HideCheckbox(ListView lvw, ListViewItem item)
{
var lviItem = new LVITEM();
lviItem.iItem = item.Index;
lviItem.mask = LVIF_STATE;
lviItem.stateMask = LVIS_STATEIMAGEMASK;
lviItem.state = 0;
SendMessage(lvw.Handle, LVM_SETITEM, IntPtr.Zero, ref lviItem);
}
private const int LVIF_STATE = 0x8;
private const int LVIS_STATEIMAGEMASK = 0xF000;
private const int LVM_FIRST = 0x1000;
private const int LVM_SETITEM = LVM_FIRST + 76;
// suppress warnings for interop
#pragma warning disable 0649
private struct LVITEM
{
public int mask;
public int iItem;
public int iSubItem;
public int state;
public int stateMask;
[MarshalAs(UnmanagedType.LPTStr)]
public String lpszText;
public int cchTextMax;
public int iImage;
public IntPtr iParam;
}
#pragma warning restore 0649
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, ref LVITEM lParam);
private void button1_Click(object sender, EventArgs e)
{
HideCheckbox(listView1, listView1.SelectedItems[0]);
}