簡體   English   中英

在C#中拖放

[英]Drag and Drop in C#

如何在C#中執行“拖動和交換”? 我希望我的第一個標簽替換第二個,反之亦然。 謝謝! 以下是我的拖放代碼-我希望可以在dragdrop方法下插入一些內容,但是我不知道如何引用要發布數據的位置。

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

創建一個DataObject實例,而不是拖動String,這樣您就可以傳遞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;
    }

}

暫無
暫無

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

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