我在表单上有一个Treeview和列表框控件。 使用以下方法处理从TreeView到ListBox的项目:
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从容器工具箱拖到我的表单上,然后将ListBox移动到TableLayoutPanel单元格之一时。 从TreeView拖动到列表框时现在发生的是this.GetChildAtPoint(targetPoint)返回TableLayoutPanel控件引用而不是ListBox控件。
有没有办法让这个.GetChildAtPoint返回列表框而不是它的容器控件?
Dankie
答案 0 :(得分: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;
答案 1 :(得分:1)
GetChildAtPoint()没有按照你的希望做到。它不会遍历嵌套控件并找到最深的嵌套控件。它只会查看 this 的子项,即表单。因此,恢复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));