【问题标题】:Drag and Drop in C#在 C# 中拖放
【发布时间】:2013-07-03 20:43:35
【问题描述】:

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

【问题讨论】:

    标签: c# drag-and-drop swap


    【解决方案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;
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-27
      • 2011-02-14
      • 2014-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多