C#在两个不同的控件之间拖放

时间:2009-11-17 20:48:30

标签: c# controls drag-and-drop

我们有一个ListView控件,可以触发DoDragDrop方法。我们有另一个控件,它是一个具有DragDrop方法的TreeView控件。问题是DragDrop方法的sender参数不是ListView,尽管ListView启动了DoDragDrop方法。相反,发件人是TreeView本身。任何关于发件人不正确的想法?

1 个答案:

答案 0 :(得分:1)

阿玛尔,

如暴政所说,“发件人”是触发事件的控件。此控件从不是启动拖动的控件,而是接受拖动的控件。

一个例子:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    /// <summary>
    /// There's button 1 and button 2... button 1 is meant to start the dragging. Button 2 is meant to accept it
    /// </summary>
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// This is when button 1 starts the drag
        /// </summary>
        private void button1_MouseDown(object sender, MouseEventArgs e)
        {
            this.DoDragDrop(this, DragDropEffects.Copy);
        }

        /// <summary>
        /// This is when button 2 accepts the drag
        /// </summary>
        private void button2_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Copy;
        }


        /// <summary>
        /// This is when the drop happens
        /// </summary>
        private void button2_DragDrop(object sender, DragEventArgs e)
        {
            // sender is always button2
        }

    }
}