现在,我能够将项目从listView 1拖到listView2。如何克隆/复制/移动项目数据?我在这里的意思的gif
widgetList是listView1。又名最右边的列表。
private void fillWidgetList()
{
widgetList.Groups.Add(new ListViewGroup("System", HorizontalAlignment.Left));
var cpu = new ListViewItem { Text = "CPU", Tag = "", Group = widgetList.Groups["System"] };
var ram = new ListViewItem { Text = "RAM", Tag = "", Group = widgetList.Groups["System"] };
widgetList.Items.Add(cpu);
widgetList.Items.Add(ram);
}
widgetCollectionList是listView2。aka中间的列表。
private void widgetList_ItemDrag(object sender, ItemDragEventArgs e)
{
DoDragDrop(e.Item, DragDropEffects.Move);
// am i suppose to save the dragged item somewhere?
}
private void widgetCollectionList_DragEnter(object sender, DragEventArgs e)
{
//e.Effect = DragDropEffects.Copy;
if (e.Data.GetDataPresent(typeof(ListViewItem)))
{
e.Effect = DragDropEffects.Move;
}
}
private void widgetCollectionList_DragDrop(object sender, DragEventArgs e)
{
widgetCollectionList.Items.Add(e.Data.ToString()); // What do i replace this with?
}
private void WidgetMaker_Load(object sender, System.EventArgs e)
{
widgetCollectionList.AllowDrop = true;
widgetCollectionList.DragDrop += new DragEventHandler(widgetCollectionList_DragDrop);
}
你快到了。您不强制将传入的对象强制转换e.Data
回LVI,而LVI对象只能属于一个对象ListView
。因此,要移动它们,您需要先将它们从旧的中删除;要复制它们,您需要克隆它们。(Groups
使这一点更加有趣:是否可以将一个素食主义者的物品放到水果组上?)
我对其进行了扩展,使其可以移动所有选定的项目,因此一次可以移动多个。如果这不是您想要的,它很容易删除。
private void lv_ItemDrag(object sender, ItemDragEventArgs e)
{
// create array or collection for all selected items
var items = new List<ListViewItem>();
// add dragged one first
items.Add((ListViewItem)e.Item);
// optionally add the other selected ones
foreach (ListViewItem lvi in lv.SelectedItems)
{
if (!items.Contains(lvi))
{
items.Add(lvi);
}
}
// pass the items to move...
lv.DoDragDrop(items, DragDropEffects.Move);
}
// this SHOULD look at KeyState to disallow actions not supported
private void lv2_DragOver(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(List<ListViewItem>)))
{
e.Effect = DragDropEffects.Move;
}
}
private void lv2_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(List<ListViewItem>)))
{
var items = (List<ListViewItem>)e.Data.GetData(typeof(List<ListViewItem>));
// move to dest LV
foreach (ListViewItem lvi in items)
{
// LVI obj can only belong to one LVI, remove
lvi.ListView.Items.Remove(lvi);
lv2.Items.Add(lvi);
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句