拖放到对象的列表框上
本文关键字:列表 对象 拖放 | 更新日期: 2023-09-27 18:27:25
我有一个Employee
List
。我只想执行简单的拖放操作。即从SourceListBox
中拖动并删除Employee
,然后将该Employee Object
添加到TargetListBox
中。我有两个问题。从源列表框中删除员工会给我一个异常,目标列表框中显示的值不是员工对象,而是字符串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)));
}
C# 从列表框中拖放的基本示例
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