实际上,您所谈论的功能不受 Winforms 而非 C# 的支持。C# 与这样的功能无关;它是 UI 技术功能而不是语言功能。但是,为了解决这个问题,我们这里的代码很少。它支持Position
每个ListViewItem
用于该目的的属性(在LargeIcon
视图中)。另一个重要的属性是AutoArrange
,这应该设置false
为允许Position
生效。这是代码:
ListViewItem heldDownItem;
Point heldDownPoint;
//MouseDown event handler for your listView1
private void listView1_MouseDown(object sender, MouseEventArgs e)
{
//listView1.AutoArrange = false;
heldDownItem = listView1.GetItemAt(e.X,e.Y);
if (heldDownItem != null) {
heldDownPoint = new Point(e.X - heldDownItem.Position.X,
e.Y - heldDownItem.Position.Y);
}
}
//MouseMove event handler for your listView1
private void listView1_MouseMove(object sender, MouseEventArgs e)
{
if (heldDownItem != null){
heldDownItem.Position = new Point(e.Location.X - heldDownPoint.X,
e.Location.Y - heldDownPoint.Y);
}
}
//MouseUp event handler for your listView1
private void listView1_MouseUp(object sender, MouseEventArgs e)
{
heldDownItem = null;
//listView1.AutoArrange = true;
}
注意:如您所见,我在那里放了 2 行注释代码行listView1.AutoArrange
,如果您不想reorder
更改ListViewItem
位置,可以取消注释这些行。我可以注意到这里有一些闪烁(当您处理 winforms ListView 时这是正常的),因此您应该使用此代码(可以放在表单构造函数中)来启用DoubleBuffered
:
typeof(Control).GetProperty("DoubleBuffered",
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance)
.SetValue(listView1, true, null);