2014-01-14 44 views
1

我在窗體上有一個TreeView和列表框控件。 從樹視圖到ListBox中刪除的項目用以下方法處理:TableLayoutControl DragNDrop問題

void ListBoxDrop(Dictionary<string, string> datasource, DragEventArgs e) 
     { 
      // Retrieve the client coordinates of the drop location. 
      Point targetPoint = this.PointToClient(new Point(e.X, e.Y)); 

      // Retrieve the listBox at the drop location. (This is where it sees a TableLayoutControl)  
      object controlAtPoint = this.GetChildAtPoint(targetPoint); 
      if (!(controlAtPoint is ListBox)) 
       return; 

      ListBox targetListbox = this.GetChildAtPoint(targetPoint) as ListBox; 

      // Retrieve the node that was dragged. 
      TreeNode draggedNode = (TreeNode)e.Data.GetData(typeof(TreeNode)); 

      // Only add the item if it doesnt already exist in the list.    
      if (!datasource.ContainsKey(draggedNode.Tag.ToString())) 
      { 
       datasource.Add(draggedNode.Tag.ToString(), draggedNode.Text); 
      } 
     } 

的問題是,當我拖到一個TableLayoutPanel從容器工具箱到我的表格,然後移到列表框到TableLayoutPanel中的細胞之一。 從TreeView拖到列表框時現在發生的事情是this.GetChildAtPoint(targetPoint)返回TableLayoutPanel控件引用而不是ListBox控件。

是否有某種方法可以獲得this.GetChildAtPoint返回列表框而不是其容器控件?

Dankie

回答

2

你將不得不改變你的this到TableLayoutPanel控件:

Point targetPoint = tlp.PointToClient(new Point(e.X, e.Y)); 
object controlAtPoint = tlp.GetChildAtPoint(targetPoint); 
if (!(controlAtPoint is ListBox)) 
    return; 
ListBox targetListbox = tlp.GetChildAtPoint(targetPoint) as ListBox; 
+0

該訣竅。謝謝。 – TheLegendaryCopyCoder

1

GetChildAtPoint()不會做你希望它做什麼。它不會遍歷嵌套控件並找到最深的嵌套控件。它只看着這個的孩子,你的表格。所以得到TableLayoutPanel是預期的結果。

所以可以自己循環,就像這樣:

Control box = this; 
    do { 
     var targetPoint = box.PointToClient(new Point(e.X, e.Y)); 
     box = box.GetChildAtPoint(targetPoint); 
     if (box == null) return; 
    } while (!(box is ListBox)); 
+0

感謝您的解釋和代碼漢斯。 – TheLegendaryCopyCoder