我正在WPF ListBoxes之间执行拖放操作,希望能在拖放的位置插入到集合中,而不是列表末尾。
有没有人知道类似于WinForms 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的拖放事件中。e对象是传递到Drop事件中的DragEventArgs对象。
IsMouseOverTarget的实现如下:
private static bool IsMouseOverTarget(Visual target, Point point)
{
var bounds = VisualTreeHelper.GetDescendantBounds(target);
return bounds.Contains(point);
}
标签
。itemsControl.InputHitTest(position).
然后调用
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)
}