-->

Drag and Drop in C#

2019-07-23 20:23发布

问题:

How do you do a "drag and swap" in c#? I want my first label to replace the second, and vice versa. Thanks! Below is my drag and drop code--I'm hoping I can insert something under the dragdrop method but I don't know how to reference where the data is being posted.

private void DragDrop_MouseDown(object sender, MouseEventArgs e)
{
    Label myTxt = (Label)sender;
    myTxt.DoDragDrop(myTxt.Text, DragDropEffects.Copy);
}
private void DragDrop_DragEnter(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.Text))
        e.Effect = e.AllowedEffect;
    else
        e.Effect = DragDropEffects.None;
}
private void DragDrop_DragDrop(object sender, DragEventArgs e)
{
    Label myTxt = (Label)sender;
    myTxt.Text = e.Data.GetData(DataFormats.Text).ToString();
}

回答1:

Instead of dragging a String, create a DataObject instance so you can pass the Label itself. You can specify your own custom format name ensuring that the contents are what you expect. Here's a quick example:

public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
    }

    private string DataFormatName = "SomeCustomDataFormatName";

    private void DragDrop_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            Label source = (Label)sender;
            DataObject data = new DataObject(DataFormatName, source);
            source.DoDragDrop(data, DragDropEffects.Copy);
        }
    }

    private void DragDrop_DragEnter(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(DataFormatName))
            e.Effect = e.AllowedEffect;
        else
            e.Effect = DragDropEffects.None;
    }
    private void DragDrop_DragDrop(object sender, DragEventArgs e)
    {
        Label target = (Label)sender;
        Label source = (Label)e.Data.GetData(DataFormatName);
        string tmp = target.Text;
        target.Text = source.Text;
        source.Text = tmp;
    }

}