ItemDragEventHandler (Delegado)
Actualización: noviembre 2007
Espacio de nombres: System.Windows.FormsEnsamblado: System.Windows.Forms (en System.Windows.Forms.dll)
/** @delegate */ public delegate void ItemDragEventHandler( Object sender, ItemDragEventArgs e )
Parámetros
- sender
- Tipo: System.Object
Origen del evento.
- e
- Tipo: System.Windows.Forms.ItemDragEventArgs
ItemDragEventArgs que contiene los datos del evento.
Cuando se crea un delegado ItemDragEventHandler, se identifica el método que controlará el evento. Para asociar el evento al controlador de eventos, se debe agregar una instancia del delegado al evento. Se llama al controlador de eventos siempre que se produce el evento, a menos que se quite el delegado. Para obtener más información acerca de delegados del controlador de eventos, vea Eventos y delegados.
En el siguiente ejemplo se muestra cómo habilitar las operaciones de arrastrar y colocar dentro de un control TreeView. En el ejemplo, se puede arrastrar cualquier nodo a otro nodo que no sea un descendiente del nodo arrastrado. El nodo arrastrado, incluidos todos sus nodos descendientes, se convierten en un nodo secundario del nodo de destino. Cuando se usa el botón primario del mouse (ratón), el nodo arrastrado se mueve al nodo de destino. Cuando se usa el botón secundario del mouse, el nodo arrastrado se copia al nodo de destino.
using System; using System.Drawing; using System.Windows.Forms; public class Form1 : Form { private TreeView treeView1; public Form1() { treeView1 = new TreeView(); this.SuspendLayout(); // Initialize treeView1. treeView1.AllowDrop = true; treeView1.Dock = DockStyle.Fill; // Add nodes to treeView1. TreeNode node; for (int x = 0; x < 3; ++x) { // Add a root node to treeView1. node = treeView1.Nodes.Add(String.Format("Node{0}", x*4)); for (int y = 1; y < 4; ++y) { // Add a child node to the previously added node. node = node.Nodes.Add(String.Format("Node{0}", x*4 + y)); } } // Add event handlers for the required drag events. treeView1.ItemDrag += new ItemDragEventHandler(treeView1_ItemDrag); treeView1.DragEnter += new DragEventHandler(treeView1_DragEnter); treeView1.DragOver += new DragEventHandler(treeView1_DragOver); treeView1.DragDrop += new DragEventHandler(treeView1_DragDrop); // Initialize the form. this.ClientSize = new Size(292, 273); this.Controls.Add(treeView1); this.ResumeLayout(false); } [STAThread] static void Main() { Application.Run(new Form1()); } private void treeView1_ItemDrag(object sender, ItemDragEventArgs e) { // Move the dragged node when the left mouse button is used. if (e.Button == MouseButtons.Left) { DoDragDrop(e.Item, DragDropEffects.Move); } // Copy the dragged node when the right mouse button is used. else if (e.Button == MouseButtons.Right) { DoDragDrop(e.Item, DragDropEffects.Copy); } } // Set the target drop effect to the effect // specified in the ItemDrag event handler. private void treeView1_DragEnter(object sender, DragEventArgs e) { e.Effect = e.AllowedEffect; } // Select the node under the mouse pointer to indicate the // expected drop location. private void treeView1_DragOver(object sender, DragEventArgs e) { // Retrieve the client coordinates of the mouse position. Point targetPoint = treeView1.PointToClient(new Point(e.X, e.Y)); // Select the node at the mouse position. treeView1.SelectedNode = treeView1.GetNodeAt(targetPoint); } private void treeView1_DragDrop(object sender, DragEventArgs e) { // Retrieve the client coordinates of the drop location. Point targetPoint = treeView1.PointToClient(new Point(e.X, e.Y)); // Retrieve the node at the drop location. TreeNode targetNode = treeView1.GetNodeAt(targetPoint); // Retrieve the node that was dragged. TreeNode draggedNode = (TreeNode)e.Data.GetData(typeof(TreeNode)); // Confirm that the node at the drop location is not // the dragged node or a descendant of the dragged node. if (!draggedNode.Equals(targetNode) && !ContainsNode(draggedNode, targetNode)) { // If it is a move operation, remove the node from its current // location and add it to the node at the drop location. if (e.Effect == DragDropEffects.Move) { draggedNode.Remove(); targetNode.Nodes.Add(draggedNode); } // If it is a copy operation, clone the dragged node // and add it to the node at the drop location. else if (e.Effect == DragDropEffects.Copy) { targetNode.Nodes.Add((TreeNode)draggedNode.Clone()); } // Expand the node at the location // to show the dropped node. targetNode.Expand(); } } // Determine whether one node is a parent // or ancestor of a second node. private bool ContainsNode(TreeNode node1, TreeNode node2) { // Check the parent node of the second node. if (node2.Parent == null) return false; if (node2.Parent.Equals(node1)) return true; // If the parent node is not null or equal to the first node, // call the ContainsNode method recursively using the parent of // the second node. return ContainsNode(node1, node2.Parent); } }
import System.*;
import System.Drawing.*;
import System.Windows.Forms.*;
public class Form1 extends Form
{
private TreeView treeView1;
public Form1()
{
treeView1 = new TreeView();
this.SuspendLayout();
// Initialize treeView1.
treeView1.set_AllowDrop(true);
treeView1.set_Dock(DockStyle.Fill);
// Add nodes to treeView1.
TreeNode node;
for (int x = 0; x < 3; ++x) {
// Add a root node to treeView1.
node = treeView1.get_Nodes().Add(String.
Format("Node{0}", (Int32)(x * 4)));
for (int y = 1; y < 4; ++y) {
// Add a child node to the previously added node.
node = node.get_Nodes().Add(String.
Format("Node{0}", (Int32)(x * 4 + y)));
}
}
// Add event handlers for the required drag events.
treeView1.add_ItemDrag(new ItemDragEventHandler(treeView1_ItemDrag));
treeView1.add_DragEnter(new DragEventHandler(treeView1_DragEnter));
treeView1.add_DragOver(new DragEventHandler(treeView1_DragOver));
treeView1.add_DragDrop(new DragEventHandler(treeView1_DragDrop));
// Initialize the form.
this.set_ClientSize(new Size(292, 273));
this.get_Controls().Add(treeView1);
this.ResumeLayout(false);
} //Form1
/** @attribute STAThread()
*/
public static void main(String[] args)
{
Application.Run(new Form1());
} //main
private void treeView1_ItemDrag(Object sender, ItemDragEventArgs e)
{
// Move the dragged node when the left mouse button is used.
if (e.get_Button().Equals(get_MouseButtons().Left)) {
DoDragDrop(e.get_Item(), DragDropEffects.Move);
}
// Copy the dragged node when the right mouse button is used.
else {
if (e.get_Button().Equals(get_MouseButtons().Right)) {
DoDragDrop(e.get_Item(), DragDropEffects.Copy);
}
}
} //treeView1_ItemDrag
// Set the target drop effect to the effect
// specified in the ItemDrag event handler.
private void treeView1_DragEnter(Object sender, DragEventArgs e)
{
e.set_Effect(e.get_AllowedEffect());
} //treeView1_DragEnter
// Select the node under the mouse pointer to indicate the
// expected drop location.
private void treeView1_DragOver(Object sender, DragEventArgs e)
{
// Retrieve the client coordinates of the mouse position.
Point targetPoint =
treeView1.PointToClient(new Point(e.get_X(), e.get_Y()));
// Select the node at the mouse position.
treeView1.set_SelectedNode(treeView1.GetNodeAt(targetPoint));
} //treeView1_DragOver
private void treeView1_DragDrop(Object sender, DragEventArgs e)
{
// Retrieve the client coordinates of the drop location.
Point targetPoint =
treeView1.PointToClient(new Point(e.get_X(), e.get_Y()));
// Retrieve the node at the drop location.
TreeNode targetNode = treeView1.GetNodeAt(targetPoint);
// Retrieve the node that was dragged.
TreeNode draggedNode =
(TreeNode)e.get_Data().GetData(TreeNode.class.ToType());
// Confirm that the node at the drop location is not
// the dragged node or a descendant of the dragged node.
if (!(draggedNode.Equals(targetNode))
&& !(ContainsNode(draggedNode, targetNode))) {
// If it is a move operation, remove the node from its current
// location and add it to the node at the drop location.
if (e.get_Effect().Equals(DragDropEffects.Move)) {
draggedNode.Remove();
targetNode.get_Nodes().Add(draggedNode);
}
// If it is a copy operation, clone the dragged node
// and add it to the node at the drop location.
else {
if (e.get_Effect().Equals(DragDropEffects.Copy)) {
targetNode.get_Nodes().Add((TreeNode)draggedNode.Clone());
}
}
// Expand the node at the location
// to show the dropped node.
targetNode.Expand();
}
} //treeView1_DragDrop
// Determine whether one node is a parent
// or ancestor of a second node.
private boolean ContainsNode(TreeNode node1, TreeNode node2)
{
// Check the parent node of the second node.
if (node2.get_Parent() == null) {
return false;
}
if (node2.get_Parent().Equals(node1)) {
return true;
}
// If the parent node is not null or equal to the first node,
// call the ContainsNode method recursively using the parent of
// the second node.
return ContainsNode(node1, node2.get_Parent());
} //ContainsNode
} //Form1
Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98
.NET Framework y .NET Compact Framework no admiten todas las versiones de cada plataforma. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.