簡體   English   中英

C#從列表框拖放到樹視圖

[英]C# Drag & drop from listbox to treeview

我有一個帶有列表框和樹視圖的winform。

一旦我的列表框中填充了項目,我想從列表框中拖動它們(多個或單個)並將它們放在樹視圖中的節點中。

如果有人在C#中有一個很好的例子。

已經有一段時間了,因為我已經搞亂了Drag / Drop,所以我想我會寫一個快速的樣本。

基本上,我有一個表單,左邊是列表框,右邊是樹視圖。 然后我在上面放了一個按鈕。 單擊該按鈕時,它只會將接下來十天的日期放入列表框中。 它還使用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位置轉換為listview項。

這里有一篇非常好的文章: 使用C#進行拖放

要在拖動時拖動項目,您需要使用COM ImageList,這在下面的文章使用ImageLists自定義拖放圖像中有詳細描述。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM