I have a winform with a listbox and a treeview.
Once my listbox is filled with items, I want to drag them (multiple or single) from the listbox and drop them in a node in the treeview.
If somebody has a good example in C# that would be great.
我已经有一段时间没有搞砸拖放了,所以我想我会写一个快速示例。
基本上,我有一个表单,左边是一个列表框,右边是一个树视图。然后我在上面放了一个按钮。单击该按钮时,它只是将接下来十天的日期放入列表框中。它还使用 2 个父节点和两个子节点填充 TreeView。然后,您只需处理所有后续的拖放事件即可使其正常工作。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.treeView1.AllowDrop = true;
this.listBox1.AllowDrop = true;
this.listBox1.MouseDown += new MouseEventHandler(listBox1_MouseDown);
this.listBox1.DragOver += new DragEventHandler(listBox1_DragOver);
this.treeView1.DragEnter += new DragEventHandler(treeView1_DragEnter);
this.treeView1.DragDrop += new DragEventHandler(treeView1_DragDrop);
}
private void button1_Click(object sender, EventArgs e)
{
this.PopulateListBox();
this.PopulateTreeView();
}
private void PopulateListBox()
{
for (int i = 0; i <= 10; i++)
{
this.listBox1.Items.Add(DateTime.Now.AddDays(i));
}
}
private void PopulateTreeView()
{
for (int i = 1; i <= 2; i++)
{
TreeNode node = new TreeNode("Node" + i);
for (int j = 1; j <= 2; j++)
{
node.Nodes.Add("SubNode" + j);
}
this.treeView1.Nodes.Add(node);
}
}
private void treeView1_DragDrop(object sender, DragEventArgs e)
{
TreeNode nodeToDropIn = this.treeView1.GetNodeAt(this.treeView1.PointToClient(new Point(e.X, e.Y)));
if (nodeToDropIn == null) { return; }
if(nodeToDropIn.Level > 0)
{
nodeToDropIn = nodeToDropIn.Parent;
}
object data = e.Data.GetData(typeof(DateTime));
if (data == null) { return; }
nodeToDropIn.Nodes.Add(data.ToString());
this.listBox1.Items.Remove(data);
}
private void listBox1_DragOver(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
}
private void treeView1_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
}
private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
this.listBox1.DoDragDrop(this.listBox1.SelectedItem, DragDropEffects.Move);
}
}
您想要使用 GetItemAt(Point point) 函数将 X、Y 位置转换为列表视图项。
这是关于它的非常好的文章:使用 C# 拖放。
要使被拖动的项目在拖动时可见,您需要使用 COM ImageList,这在以下文章使用 ImageLists 自定义拖放图像中有很好的描述。
您能否编辑您的帖子并准确告诉我们您的哪一部分有问题?这里的人往往不会很好地回答“请发送 codz”类型的问题
非常感谢你做的这些。我只需要一个代码示例来确认我没有在 Mono 中获得拖放“效果”(至少在 OSX 上)。您出色而完整的示例为我节省了大量工作。
您好,我尝试了您的代码,但由于某种原因,被拖动的项目总是被添加到树的根(第一个)节点。返回nodeToDropIn.Text正确的节点名称,但项目被添加到父节点。可能是什么问题?