在 C# 中验证 TreeView 拖/放操作的最佳方法
-
01-07-2019 - |
题
我想验证是否允许拖放操作。有效的项目可以来自我们的另一个“控件”,或者来自自定义树视图内部。目前我有这个:
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;
}
我已将所有检查代码移至此方法以尝试改进,但对我来说这仍然很可怕!
如此多的逻辑,以及如此多的逻辑来完成我期望树视图能够自行完成的事情(例如,“TargetExistsInNode”检查拖动的节点是否被拖动到其子节点之一)。
验证控件输入的最佳方法是什么?
解决方案
我使用 TreeNode.Tag 属性来存储构成逻辑的小型“控制器”对象。例如。:
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;
}
}
那么我的 CanDrop 会是这样的:
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;
}
现在,对于添加到树中的每一类对象,我可以通过选择将哪个 TreeNodeController 放入 Tag 对象来专门化其行为。
其他提示
没有严格回答您的问题,但我发现您的代码中存在错误。DragDropEffects
设置了 flags 属性,这样你就可以得到 e.Effect
是复制和移动的按位组合。在这种情况下,您的代码将错误地返回 false。
不隶属于 StackOverflow