[英]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中刪除該項目。
列表視圖通常沒有拖放功能。 但是您可以通過一些額外的代碼來進行一些更改來進行拖放。 這是幫助您解決問題的鏈接。 我希望你能從中得到一些東西。
調用DoDragDrop
,您正在分配數據。 讓您的自定義數據對象,而不是ListViewItem
。
如果需要ListViewItem
,則將對它的引用添加到自定義數據類中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.