在C#中拖放 [英] Drag and Drop in C#
本文介绍了在C#中拖放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您如何在c#中执行拖动和交换?我希望第一个标签替换第二个标签,反之亦然。谢谢!下面是我的拖放代码-我希望可以在dragdrop方法下插入一些内容,但是我不知道如何引用要发布数据的位置。
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();
}
推荐答案
不是拖动字符串,创建一个 DataObject
实例,以便您可以传递 Label
本身。您可以指定自己的自定义格式名称,以确保内容符合预期。这是一个简单的示例:
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;
}
}
这篇关于在C#中拖放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文