WPF ListBox IndexFromPoint

梦想与她 提交于 2019-12-22 09:07:01

问题


I am performing a drag drop between WPF ListBoxes and I would like to be able to insert into the collection at the position it is dropped rather than the end of the list.

Does anyone know of a solution that is similar to the WinForms ListBox IndexFromPoint function?


回答1:


I ended up getting this work by using a combination of DragDropEvent.GetPosition, VisualTreeHelper.GetDescendantBounds and Rect.Contains. Here's what I came up with:

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;
   }
}

The code resides in the ListBox Drop event. The e object is the DragEventArgs object passed into the Drop event.

The implementation for IsMouseOverTarget is:

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



回答2:


You can use

itemsControl.InputHitTest(position).

Go up the visual tree from there until you hit the correct ItemContainer (for ListBox you would find ListBoxItem, etc....)

Then call

itemsControl.ItemContainerGenerator.IndexFromContainer(listBoxItem) 

to get the index for insertion.




回答3:


This is how I do it - no drama with iterating the list etc

//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)
}

That is the gist - you can then use ItemContainerGenerator.ContainerFromItem or/and IndexFromContainer to get index - but I suspect most want to use the Item



来源:https://stackoverflow.com/questions/6961963/wpf-listbox-indexfrompoint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!