我正在 WPF 列表框之间执行拖放操作,我希望能够在拖放位置而不是列表末尾处插入到集合中。
有人知道类似于 WinForms ListBox IndexFromPoint 函数的解决方案吗?
最佳答案
我最终通过组合使用 DragDropEvent.GetPosition、VisualTreeHelper.GetDescendantBounds 和 Rect.Contains 完成了这项工作。这是我想出的:
int index = -1;
for (int i = 0; i < collection.Count; i++)
{
var lbi = listBox.ItemContainerGenerator.ContainerFromIndex(i) as ListBoxItem;
if (lbi == null) continue;
if (IsMouseOverTarget(lbi, e.GetPosition((IInputElement)lbi)))
{
index = i;
break;
}
}
代码驻留在 ListBox Drop 事件中。 e 对象是传递给 Drop 事件的 DragEventArgs 对象。
IsMouseOverTarget 的实现是:
private static bool IsMouseOverTarget(Visual target, Point point)
{
var bounds = VisualTreeHelper.GetDescendantBounds(target);
return bounds.Contains(point);
}
关于c# - WPF 列表框 IndexFromPoint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6961963/