2014-01-23 32 views
0

我想使用两个Listviews(AllListView和PreListView)之间的拖放。这是我没走多远:Listviews和拖放在C#

在该AllListView装满物品的功能,我用类似的东西assosiate的myCustomDataObject到单个ListViewItem的:

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

有我的事件处理程序2名列表视图:

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

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

回答

4

您正在拖动ListViewItem类型的对象。所以你首先要检查拖动的项目是否属于这种类型。你可能想要确定它是一种快乐的物品,它具有适当的标签值。因此:

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中删除项目。

+0

**谢谢!!! – Tagamoga

0

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

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

+0

我的亲爱的,这个链接适合有这种症状的人:“..你不能通过在运行时拖动ListView控件中的项目来重新排序项目。”**点重新排序**和WITHIN一个ListView ...并确保Listviews具有拖放功能。否则,他们不会有像“OnDragDrop”命名的事件处理程序... ;-) – Tagamoga

0

当你调用DoDragDrop,要指定数据。制作而不是ListViewItem

如果您需要ListViewItem,请将其引用添加到您的自定义数据类中。

+0

其实我不需要ListViewItem ...所以我改变了base.DoDragDrop(** lst_All.SelectedItems [0] **, DragDropEffects.Move); doDragDrop(** lst_All.SelectedItems [0] .Tag **,DragDropEffects.Move);但是在OnPreDragEnter和OnPreDragDrop中,函数“e.Data.GetData(typeof(myCustomData))”返回null,“e.Data.GetDataPresent(typeof(myCustomData))”返回false。我的错误在哪里? – Tagamoga

+0

汉斯对这个问题有正确的答案。 – DonBoitnott