繁体   English   中英

C#中的Listview和拖放

[英]Listviews And Drag and Drop in C#

我想在两个Listview(AllListView和PreListView)之间使用拖放。 这是我得到的结果:

在AllListView充满Items的函数中,我使用类似的方法将myCustomDataObject关联到单个ListviewItem:

ListViewItem newItem = new ListViewItem();
newItem.Text = myCustomDataObject.getName();
newItem.Tag = myCustomDataObject;
lst_All.Items.Add(newItem);

我有两个列表视图的事件处理程序:

AllListView:

private void OnAllDragEnter(object sender, DragEventArgs e)
{
    e.Effect = DragDropEffects.All;
    // How Do I add my CustomDataObject?
}

private void OnAllItemDrag(object sender, ItemDragEventArgs e)
{
    base.DoDragDrop(lst_All.SelectedItems[0], DragDropEffects.Move);
    // Do I have to Do something to pass my CustomDataObject?
}

PreListView:

private void OnPreDragEnter(object sender, DragEventArgs e)
{
    //If there one of myCustomDataObject go on
    e.Effect = DragDropEffects.Move;
}

private void OnPreDragDrop(object sender, DragEventArgs e)
{
    // Get Here myCustomDataObject to generate the new Item
    lst_Pre.Items.Add("Done...");
}

所以我的问题是,如何实现在“ OnPreDragDrop”中找到myCustomDataObject。 我已经尝试了许多版本的e.Data.Getdata()和e.Data.Setdata(),但是距离还很远。

您正在拖动类型为ListViewItem的对象。 因此,您首先要检查被拖动的项目确实是该类型的项目。 并且您可能想要确保它是一种快乐的物品,它具有正确的Tag值。 从而:

private void OnPreDragEnter(object sender, DragEventArgs e) {
    if (e.Data.GetDataPresent(typeof(ListViewItem))) {
        var item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
        if (item.Tag is CustomDataObject) {
            e.Effect = DragDropEffects.Move;
        }
    }
}

在Drop事件中,您实际上要实现逻辑的“移动”操作,将项目从源ListView中删除,然后将其添加到目标ListView中。 不再需要检查,您已经在DragEnter事件处理程序中执行了检查。 从而:

private void OnPreDragDrop(object sender, DragEventArgs e) {
    var item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
    item.ListView.Items.Remove(item);
    lst_Pre.Items.Add(item);
}

请注意,您可能一分钟都认为错误是拖动ListViewItem而不是CustomDataObject。 并非如此,拖动ListViewItem可以轻松地从源ListView中删除该项目。

列表视图通常没有拖放功能。 但是您可以通过一些额外的代码来进行一些更改来进行拖放。 这是帮助您解决问题的链接。 我希望你能从中得到一些东西。

http://support.microsoft.com/kb/822483

调用DoDragDrop ,您正在分配数据。 让您自定义数据对象,而不是ListViewItem

如果需要ListViewItem ,则将对它的引用添加到自定义数据类中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM