WPF ListBox IndexFromPoint

Jos*_*osh 4 c# wpf wpf-controls

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

有没有人知道类似于WinForms ListBox IndexFromPoint函数的解决方案?

Jos*_*osh 7

我最终通过使用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;
   }
}
Run Code Online (Sandbox Code Playgroud)

代码驻留在ListBox Drop事件中.e对象是传递给Drop事件的DragEventArgs对象.

IsMouseOverTarget的实现是:

private static bool IsMouseOverTarget(Visual target, Point point)
{
    var bounds = VisualTreeHelper.GetDescendantBounds(target);
    return bounds.Contains(point);
}
Run Code Online (Sandbox Code Playgroud)