DevExpress TreeList 禁止节点拖动到其他节点上

背景

在做一个类似文件树的控件,支持节点从树上向其它的控件拖动程序,但是要保证树上的节点不能拖动上其他的节点上。

代码

        /// <summary>
        /// 拖动节点完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeList_ShowProjectFolder_DragOver(object sender, DragEventArgs e)
        {
            TreeListNode pTreeListNode = GetNodeByLocation(treeList_ShowProjectFolder, new System.Drawing.Point(e.X, e.Y));
            if (pTreeListNode != null)
            {
                // 设置拖动效果
                e.Effect = DragDropEffects.None;
                return;
            }
        }
        /// <summary>
        /// 获取到鼠标位置的树节点
        /// </summary>
        /// <param name="treeList"></param>
        /// <param name="location"></param>
        /// <returns></returns>
        private TreeListNode GetNodeByLocation(TreeList treeList, System.Drawing.Point location)
        {
            // 判断当前鼠标位置是否探测到树的节点
            TreeListHitInfo hitInfo = treeList.CalcHitInfo(treeList.PointToClient(location));
            return hitInfo.Node;
        }

思路

在TreeList的DragOver的事件下添加代码,判断DragOver时鼠标是否与树的节点相交,如果相交,则将拖动的效果变为禁止进入。这里DragEffects是一个枚举。用来表示节点拖动所产生的结果。

namespace System.Windows.Forms
{
    // 摘要:
    //     指定拖放操作的可能效果。
    [Flags]
    public enum DragDropEffects
    {
        // 摘要:
        //     拖动时可以滚动目标,以定位在目标中当前不可见的某个放置位置。
        Scroll = -2147483648,
        //
        // 摘要:
        //     System.Windows.DragDropEffects.Copy、System.Windows.Forms.DragDropEffects.Move
        //     和 System.Windows.Forms.DragDropEffects.Scroll 效果的组合。
        All = -2147483645,
        //
        // 摘要:
        //     放置目标不接受该数据。
        None = 0,
        //
        // 摘要:
        //     将拖动源中的数据复制到放置目标。
        Copy = 1,
        //
        // 摘要:
        //     将拖动源的数据移动到放置目标。
        Move = 2,
        //
        // 摘要:
        //     将拖动源中的数据链接到放置目标。
        Link = 4,
    }
}
原文地址:https://www.cnblogs.com/MaFeng0213/p/8059580.html