在列表框对象上拖放

时间:2015-12-20 14:55:28

标签: c# wpf object drag-and-drop listbox

我有List Employee。我只是想执行简单的拖放操作。即从Employee拖放SourceListBox并在Employee Object中添加TargetListBox。 我有两个问题。 从SourceListBox中删除员工给了我一个例外,TargetListBox中显示的值不是Employee对象,而是字符串Drag_and_Drop.Employee

       private List<Employee> emp = new List<Employee>();
 emp.Add(new Employee { EmployeeId = 1, Name = "Arslan" });
            emp.Add(new Employee { EmployeeId = 2, Name = "Talha" });

 SourceListBox.ItemsSource = emp;
            SourceListBox.DisplayMemberPath = "Name";
            SourceListBox.SelectedValuePath = "EmployeeId";

 private void SourceListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {   

            DragDropEffects dde = DragDrop.DoDragDrop(SourceListBox, SourceListBox.SelectedItem, DragDropEffects.All);

            var empi = (Employee) SourceListBox.SelectedItem;

            if(dde == DragDropEffects.All)
            {
                emp.Remove(empi);
                SourceListBox.ItemsSource = null;
                SourceListBox.ItemsSource = emp;
            }
        }

   private void TargetListBox_DragEnter(object sender, DragEventArgs e)
        {
            e.Effects = DragDropEffects.All;
            TargetListBox.Items.Add(e.Data.GetData(typeof(Employee)));
        }

1 个答案:

答案 0 :(得分:0)

C# Drag and Drop From listBox

的基本示例
public object lb_item = null;   

private void listBox1_DragLeave(object sender, EventArgs e)
{
    ListBox lb = sender as ListBox;

    lb_item = lb.SelectedItem;
    lb.Items.Remove(lb.SelectedItem);
}

private void listBox1_DragEnter(object sender, DragEventArgs e)
{       
    if (lb_item != null)
    {
        listBox1.Items.Add(lb_item);
        lb_item = null;
    }
}


private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
    lb_item = null;

    if (listBox1.Items.Count == 0)
    {
        return;
    }                

    int index = listBox1.IndexFromPoint(e.X, e.Y);
    string s = listBox1.Items[index].ToString();
    DragDropEffects dde1 = DoDragDrop(s, DragDropEffects.All);      
}

private void Form1_DragDrop(object sender, DragEventArgs e)
{            
    lb_item = null;
}

并扩展知识http://www.codeproject.com/Articles/5883/Two-ListBoxes-Drag-and-Drop-Example