C# WPF列表框IndexFromPoint

C# WPF列表框IndexFromPoint,c#,wpf,wpf-controls,C#,Wpf,Wpf Controls,我正在WPF列表框之间执行拖放操作,我希望能够将其插入到集合中的拖放位置,而不是列表的末尾 有人知道类似于WinForms ListBox IndexFromPoint函数的解决方案吗?您可以使用 itemsControl.InputHitTest(position). 从那里向上浏览可视化树,直到找到正确的ItemContainer(对于ListBox,您将找到ListBoxItem,等等) 然后打电话 itemsControl.ItemContainerGenerator.IndexFro

我正在WPF列表框之间执行拖放操作,我希望能够将其插入到集合中的拖放位置,而不是列表的末尾

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

您可以使用

itemsControl.InputHitTest(position).
从那里向上浏览可视化树,直到找到正确的ItemContainer(对于ListBox,您将找到ListBoxItem,等等)

然后打电话

itemsControl.ItemContainerGenerator.IndexFromContainer(listBoxItem) 

获取插入的索引。

我最终通过使用DragDropEvent.GetPosition、visualtreeheloper.getgenderantbounds和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;
   }
}

我就是这样做的-没有戏剧化的重复列表等

//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来获取索引-但我怀疑大多数人都想使用该项

这可能会有所帮助:我刚刚尝试了这个,但可能我做错了什么。我看到的是InAuthitTest返回给我一个文本块,它不允许我比较ListBoxItem。我假设是因为我的ListBox绑定到一个可观察的字符串集合。不,继续从textblock调用VisualTreeHelper.GetParent(dependencyObject)(递归地,即将调用的结果传递回该方法),直到你点击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)
}