WPF ListBox IndexFromPoint

2019-05-05 19:26发布

问题:

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