WPF ListBox IndexFromPoint

我正在WPF ListBoxes之间执行拖放操作,我希望能够在它被删除的位置插入集合而不是列表的末尾。

有没有人知道类似于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); } 

您可以使用

 itemsControl.InputHitTest(position). 

从那里上到可视树,直到你找到正确的ItemContainer(对于ListBox,你会找到ListBoxItem,等等….)

然后打电话

 itemsControl.ItemContainerGenerator.IndexFromContainer(listBoxItem) 

获取插入索引。

这就是我这样做的方式 – 没有重复列表的戏剧等

 //Get the position var currp = e.GetPosition(dgrid); //Get whats under that position var elem=dgrid.InputHitTest(currp); //Your ListView or DataGrid will have set the DataContext to your bound item if (elem is FrameworkElement && (elem as FrameworkElement).DataContext != null) { var target=dgrid.ItemContainerGenerator.ContainerFromItem((elem as FrameworkElement).DataContext) } 

这就是要点 – 然后你可以使用ItemContainerGenerator.ContainerFromItem或/和IndexFromContainer获取索引 – 但我怀疑大多数人都想使用Item