编程语言
首页 > 编程语言> > c# – 将ListView项从一个listView拖放到另一个listView

c# – 将ListView项从一个listView拖放到另一个listView

作者:互联网

现在,我可以将项目从listView 1拖到listView 2.如何克隆/复制/移动项目的数据? Gif of what i mean here

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.又名中间的名单.

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.所以,为了移动它们,你需要先从旧的移除它们;复制它们,你需要克隆它们. (小组让这个更有趣:素食项目可以放到水果组吗?)

我将其展开以允许它移动所有选定的项目,以便一次可以移动多个项目.如果这不是你想要的,它很容易删除.

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);
        }
    }
}

标签:c,net,winforms,listview,listviewitem
来源: https://codeday.me/bug/20190519/1134882.html