1

你如何在 C# 中进行“拖放”?我希望我的第一个标签替换第二个,反之亦然。谢谢!下面是我的拖放代码——我希望我可以在拖放方法下插入一些东西,但我不知道如何引用数据的发布位置。

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();
}
4

1 回答 1

1

不要拖动字符串,而是创建一个DataObject实例,以便您可以传递它Label本身。您可以指定自己的自定义格式名称,以确保内容符合您的预期。这是一个简单的例子:

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;
    }

}
于 2013-07-03T21:11:13.717 回答