- A+
实现逻辑,winform程序Dev TreeList控件上下级拖拽,选中节点可以拖拽至他的同级节点或上级节点,不可拖拽至他的下级几点
如下图:m01节点可以拖拽至root节点外面或者my节点下,但不可拖拽至m01-1和m01-2节点下
实现关键代码:
treeList.AllowDrop =true; //是否允许拖拽
需要的五个事件
详细代码:
//移过组件
private void treeListFunc_MouseMove(object sender, MouseEventArgs e)
{
TreeList treelist = sender as TreeList;
if (e.Button == MouseButtons.Left && downHitInfo != null)
{
if (treeListFunc.Selection.Count == 0)
return;
Size dragSize = SystemInformation.DragSize;
Rectangle dragRect = new Rectangle(new Point(downHitInfo.MousePoint.X - dragSize.Width / 2,
downHitInfo.MousePoint.Y - dragSize.Height / 2), dragSize);
if (!dragRect.Contains(new Point(e.X, e.Y)))
{
List<TreeListNode> node = new List<TreeListNode>();
foreach (TreeListNode n in treeListFunc.Selection)
{
node.Add(n);
}
treelist.DoDragDrop(node, DragDropEffects.Copy);
downHitInfo = null;
DevExpress.Utils.DXMouseEventArgs.GetMouseArgs(e).Handled = true;
}
}
}
//按下鼠标
private void treeListFunc_MouseDown(object sender, MouseEventArgs e)
{
TreeList treelist = sender as TreeList;
downHitInfo = null;
TreeListHitInfo hitInfo = treelist.CalcHitInfo(new Point(e.X, e.Y));
if (Control.ModifierKeys != Keys.None) return;
if (e.Button == MouseButtons.Left)
{
downHitInfo = hitInfo;
}
}
//拖至边界
private void treeListFunc_DragOver(object sender, DragEventArgs e)
{
TreeList treelist = sender as TreeList;
if (treelist != null)
{
e.Effect = DragDropEffects.Copy;
}
}
//拖放时
private void treeListFunc_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}
//拖放完成
private void treeListFunc_DragDrop(object sender, DragEventArgs e)
{
List<TreeListNode> nodes = (List<TreeListNode>)e.Data.GetData(typeof(List<TreeListNode>));
TreeList grid = sender as TreeList;
DataTable table = grid.DataSource as DataTable;
if (nodes != null && nodes.Count > 0 && table != null)
{
//移动至节点
TreeListHitInfo info = treeListFunc.CalcHitInfo(treeListFunc.PointToClient(new System.Drawing.Point(e.X, e.Y)));
TreeListNode nodeTo = info.Node;
foreach (TreeListNode node in nodes)
{
string currCode = node.GetValue("Code").ConvertTo("");
var dr1 = dsMain.Tables[0].Select().Where(a => a["Code"].ConvertTo("") == currCode);
DataRow[] dr = dsMain.Tables[0].Select($"Code='{currCode}'");
if (dr.Length >= 1)
{
//拖放节点未找到
if (nodeTo == null)
{
dr[0]["Upper_ID"] = Guid.Empty.ToString();
dr[0]["Upper_Code"] = "";
dr[0]["Upper_Name"] = "";
}
else
{
string currCodeTo = nodeTo.GetValue("Code").ConvertTo("");
//当不存在目标节点或目标节点的层级大于等于被拖动节点时(后者仅针对树内拖拽),显示禁止图标
if (currCode == "" || currCode == currCodeTo || nodeTo.HasAsParent(node))
{
e.Effect = DragDropEffects.None;
return;
}
dr[0]["Upper_ID"] = nodeTo.GetValue("ID").ConvertTo(Guid.Empty.ToString());
dr[0]["Upper_Code"] = nodeTo.GetValue("Code").ConvertTo(Guid.Empty.ToString());
dr[0]["Upper_Name"] = nodeTo.GetValue("Name").ConvertTo(Guid.Empty.ToString());
}
PageHelper.SetMenuImage(treeListFunc);
}
}
}
}
最终效果展示: