2014-01-23 30 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