WPF列表框IndexFromPoint [英] WPF ListBox IndexFromPoint
问题描述
我执行WPF列表框和I之间的拖放希望能够插入在它被丢弃,而不是列表的末尾位置集合
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.
有谁知道一个解决方案,就是类似的WinForms ListBox中IndexFromPoint功能?
Does anyone know of a solution that is similar to the WinForms ListBox IndexFromPoint function?
推荐答案
我最终得到这个工作通过使用DragDropEvent.GetPosition,VisualTreeHelper.GetDescendantBounds和Rect.Contains的组合。以下是我想出了:
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;
}
}
中的代码驻留在列表框Drop事件。 。电子对象传递到Drop事件DragEventArgs对象
The code resides in the ListBox Drop event. The e object is the DragEventArgs object passed into the Drop event.
有关IsMouseOverTarget的实现是:
The implementation for IsMouseOverTarget is:
private static bool IsMouseOverTarget(Visual target, Point point)
{
var bounds = VisualTreeHelper.GetDescendantBounds(target);
return bounds.Contains(point);
}
这篇关于WPF列表框IndexFromPoint的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!