C #: controlos gota arrasto na superfície
-
05-07-2019 - |
Pergunta
Existe uma maneira que se pode fazer um controle, como uma caixa de texto, arraste-droppable em C #?
Eu quero que o usuário tenha a capacidade de clicar e segurar o controle com o mouse e arrastá-la em sua superfície e soltá-lo em qualquer lugar dentro dessa superfície.
Alguém tem alguma idéia de como implementar isso?
Solução
Esta resposta me ajudou a muitos. É ótimo trabalhar em qualquer tipo de Controle e Container.
Outras dicas
Se o seu controle está se movendo dentro de um recipiente (por exemplo painel), você pode substituir OnMouseDown / eventos OnMouseMove, e ajustar a propriedade Localização do controle.
Com base na sua pergunta, não parece que você precisa drag-and-drop completo (mover dados entre diferentes controles ou até mesmo aplicativos).
Se você está tentando arrastar um item de fora do recipiente Silverlight, então sua melhor aposta é o de verificar Silverlight 4 beta
public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
// wire up the various Drop events
InstallButton.Drop += new DragEventHandler(InstallButton_Drop);
InstallButton.DragOver += new DragEventHandler(InstallButton_DragOver);
InstallButton.DragEnter += new DragEventHandler(InstallButton_DragEnter);
InstallButton.DragLeave += new DragEventHandler(InstallButton_DragLeave);
}
void InstallButton_Drop(object sender, DragEventArgs e)
{
IDataObject foo = e.Data; // do something with data
}
Isto costumava ser tão fácil em VB6. Mas agora nós realmente só tem o que costumava ser chamado de OLEDrag.
De qualquer maneira, o código seguinte deve mostrar-lhe como. Você só precisa de uma única etiqueta ( dragDropLabel ), e definir o AllowDrop de propriedades do formulário ( DragDropTestForm ) para True.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace DragDropTest
{
public partial class DragDropTestForm : Form
{
// Negative offset to drop location, to adjust for position where a drag starts
// on a label.
private Point _labelOffset;
// Save the full type name for a label, since this is used to test for the control type.
private string labelTypeName = typeof(Label).FullName;
public DragDropTestForm()
{
InitializeComponent();
}
private void dragDropLabel_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
_labelOffset = new Point(-e.X, -e.Y);
}
}
private void dragDropLabel_MouseMove(object sender, MouseEventArgs e)
{
const double minimumDragDistance = 4;
const double minimumDragDistanceSquared = minimumDragDistance * minimumDragDistance;
if (e.Button == MouseButtons.Left)
{
// Minimum n pixel movement before drag starts.
if (((Math.Pow(_labelOffset.X - e.X, 2)) + Math.Pow(_labelOffset.Y - e.Y, 2)) >= minimumDragDistanceSquared)
{
dragDropLabel.DoDragDrop(dragDropLabel, DragDropEffects.Move);
}
}
}
private void DragDropTestForm_DragOver(object sender, DragEventArgs e)
{
IDataObject data = e.Data;
string[] formats = data.GetFormats();
if (formats[0] == labelTypeName)
{
e.Effect = DragDropEffects.Move;
}
}
private void DragDropTestForm_DragDrop(object sender, DragEventArgs e)
{
IDataObject data = e.Data;
string[] formats = data.GetFormats();
if (formats[0] == labelTypeName)
{
Label label = (Label) data.GetData(formats[0]);
if (label == dragDropLabel)
{
Point newLocation = new Point(e.X, e.Y);
newLocation.Offset(_labelOffset);
dragDropLabel.Location = this.PointToClient(newLocation);
}
}
}
}
}