DevExpress學習筆記(五)-以拖拽的方式構建樹(TreeList)


 

DevExpress學習筆記

以拖拽的方式構建樹(TreeList)

本人最近在做某個項目中需要用到動態設置TreeList節點的技術,在這個過程中對於TreeList的各項功能有了初步的嘗試,准備分幾篇內容將其記錄下來。這一篇主要記錄TreeList的拖拽功能。

一 ImageListBoxControl 至 TreeList

在Visual Studio新建一個Form,並且將ImageListBoxControl和TreeList兩個控件分別拖到這個Form上,設置相關屬性.涉及到拖拽必然會有源控件和目標控件,需要設置目標控件的AllowDrop屬性為True,在此處就需要設置TreeList的AllowDrop屬性為True。

下面開始ImageListBoxControl的初始化操作。我們模仿邏輯運算符,添加3個“與、或、非”的邏輯圖標到ImageListBoxControl,界面效果如下:

 

我們需要做的工作就是將上面的三個節點拖拽至TreeList中,生成三個樹節點。主要分為三個步驟來做。

首先,需要為ImageListBoxControl新增三個事件相應函數,分別為MouseDown,MouseMove和GiveFeedback。這三個函數的含義為MouseDown和MouseMove表示鼠標的按鍵和拖動的事件,GiveFeedback表示在鼠標拖動時,控件給予系統請求的響應。實現代碼如下:

View Code
 1 private void imageListBoxControl1_MouseDown(object sender, MouseEventArgs e)
 2 
 3         {
 4 
 5             //獲取當前鼠標選擇的項目Index
 6 
 7             int index = imageListBoxControl1.IndexFromPoint(new Point(e.X, e.Y));
 8 
 9             if (index >= 0)
10 
11             {
12 
13 //根據index獲取選擇的Item
14 
15                 newItem = imageListBoxControl1.Items[index];
16 
17             }
18 
19         }
20 
21  
22 
23         private void imageListBoxControl1_MouseMove(object sender, MouseEventArgs e)
24 
25         {
26 
27             if (newItem == null || e.Button != MouseButtons.Left) return;
28 
29          //ImageListBoxControl拖拽響應事件,LogicDragObject為自定義的邏輯操作Item類。
30 
31             imageListBoxControl1.DoDragDrop(new LogicDragObject(newItem.ImageIndex,++groupNum), DragDropEffects.Copy);
32 
33         }
34 
35  
36 
37         private void imageListBoxControl1_GiveFeedback(object sender, GiveFeedbackEventArgs e)
38 
39         {
40 
41             e.UseDefaultCursors = false;
42 
43         }

 

   其次,新增TreeList控件的DragDrop、GiveFeedback和DragOver三個響應事件。

DragDrop的事件部分代碼如下:

TreeListHitInfo hi = treeList1.CalcHitInfo(treeList1.PointToClient(new Point(e.X, e.Y)));

            LogicDragObject dobj = GetDragObject(e.Data);

            //拖放邏輯操作符

                TreeListNode node = hi.Node;

                if (hi.HitInfoType == HitInfoType.Empty || node != null)

                {

                    node = treeList1.AppendNode(dobj.LogicDragData, node);

                    node.StateImageIndex = dobj.ImageIndex;

                    treeList1.MakeNodeVisible(node);

                }

 

拖拽的本質就是由CalcHitInfo獲取當前放置的節點,由GetDragObject(e.Data)獲取到需要放置的Data,通過AppendNode添加Node,最后MakeNodeVisible使Node可見。

效果示意圖如下:

 

二 TreeList至LabelControl

現在我想實現以拖拽的方式刪除樹節點的操作。首先,放置一個LabelControl,並且將其設置為回收站的圖標。和上面一樣,需要將LabelControl的AllowDrop屬性設置為True。然后需要實現DragDrop、DragEnter和DragLeave三個響應事件。

DragDrop的部分實現代碼如下:

      

 //獲取需要刪除的樹節點,e.Data為獲取到的TreeList的拖拽節點

           TreeListNode node = GetDragNode(e.Data);

            if (node != null)

            {

                treeList1.DeleteNode(node);

            }

            SetDefaultLabel(); 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM