Pregunta

Quiero verificar que se permita la operación de arrastrar y soltar.Un elemento válido puede provenir de otro de nuestros "controles" o internamente desde la vista de árbol personalizada.Actualmente tengo esto:

bool CanDrop(DragEventArgs e)
{
    bool allow = false;
    Point point = tree.PointToClient(new Point(e.X, e.Y));
    TreeNode target = tree.GetNodeAt(point);
    if (target != null)
    {
        if (CanWrite(target)) //user permissions
        {
            if (e.Data.GetData(typeof(DataInfoObject)) != null) //from internal application
            {
                DataInfoObject info = (DataInfoObject)e.Data.GetData(typeof(DataInfoObject));
                DragDataCollection data = info.GetData(typeof(DragDataCollection)) as DragDataCollection;
                if (data != null)
                {
                    allow = true;
                }
            }
            else if (tree.SelectedNode.Tag.GetType() != typeof(TreeRow)) //node belongs to this & not a root node
            {
                if (TargetExistsInNode(tree.SelectedNode, target) == false)
                {
                    if (e.Effect == DragDropEffects.Copy)
                    {
                        allow = true;
                    }
                    else if (e.Effect == DragDropEffects.Move)
                    {
                        allow = true;
                    }
                }
            }
        }
    }
    return allow;
}

Moví todo el código de verificación a este método para intentar mejorar las cosas, ¡pero para mí esto sigue siendo horrible!

Tanta lógica, y tanta para hacer cosas que esperaría que la vista de árbol hiciera por sí sola (p. ej."TargetExistsInNode" comprueba si el nodo arrastrado se está arrastrando a uno de sus hijos).

¿Cuál es la mejor manera de validar la entrada a un control?

¿Fue útil?

Solución

Utilizo la propiedad TreeNode.Tag para almacenar pequeños objetos "controladores" que componen la lógica.P.ej.:

class TreeNodeController {
  Entity data; 

  virtual bool IsReadOnly { get; }
  virtual bool CanDrop(TreeNodeController source, DragDropEffects effect);
  virtual bool CanDrop(DataInfoObject info, DragDropEffects effect);
  virtual bool CanRename();
}

class ParentNodeController : TreeNodeController {
  override bool IsReadOnly { get { return data.IsReadOnly; } } 
  override bool CanDrop(TreeNodeController source, DragDropEffect effect) {
    return !IsReadOnly && !data.IsChildOf(source.data) && effect == DragDropEffect.Move;
  }
  virtual bool CanDrop(DataInfoObject info, DragDropEffects effect) {
    return info.DragDataCollection != null;
  }
  override bool CanRename() { 
    return !data.IsReadOnly && data.HasName;
  }
}

class LeafNodeController : TreeNodeController {
  override bool CanDrop(TreeNodeController source, DragDropEffect effect) {
    return false;
  }
}

Entonces mi CanDrop sería algo como:

bool CanDrop(DragDropEventArgs args) {
  Point point = tree.PointToClient(new Point(e.X, e.Y));
  TreeNode target = tree.GetNodeAt(point);
  TreeNodeController targetController = target.Tag as TreeNodeController;

  DataInfoObject info = args.GetData(typeof(DataInfoObject)) as DataInfoObject;
  TreeNodeController sourceController = args.GetData(typeof(TreeNodeController)) as TreeNodeController;

  if (info != null) return targetController.CanDrop(info, e.Effect);
  if (sourceController != null) return targetController.CanDrop(sourceController, e.Effect);
  return false;
}

Ahora, para cada clase de objetos que agrego al árbol, puedo especializar el comportamiento eligiendo qué TreeNodeController poner en el objeto Tag.

Otros consejos

No respondo estrictamente a tu pregunta, pero detecté un error en tu código.DragDropEffects tiene el atributo flags configurado para que puedas obtener e.Effect ser una combinación bit a bit de copiar y mover.En cuyo caso su código devolvería incorrectamente falso.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top