我想在两个Listviews(AllListView和PreListView)之间使用拖放。这是我得到了多远:
在AllListView用Items填充的函数中,我使用类似的东西来将myCustomDataObject与单个ListviewItem相关联:
ListViewItem newItem = new ListViewItem();
newItem.Text = myCustomDataObject.getName();
newItem.Tag = myCustomDataObject;
lst_All.Items.Add(newItem);
我有两个Listviews的Eventhandler:
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(),但我没有走得太远。
答案 0 :(得分:5)
您正在拖动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事件中,您实际上想要实现逻辑“Move”操作,从源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中删除该项目。
答案 1 :(得分:0)
列表视图通常没有拖放功能。但你可以通过一些额外的代码进行一些更改来拖放。这是一个帮助您解决问题的链接。我希望你能从中获得一些东西。
答案 2 :(得分:0)
当您致电DoDragDrop
时,您正在分配数据。 那您的自定义数据对象而不是ListViewItem
。
如果您需要ListViewItem
,请将其引用添加到自定义数据类。