I have 2 ListViews, I can drag an item from ListView1 and drop it on to ListView2. If I drop the item between other items I want the item to be added in that same location.
So the question is: How do I get the position/index where I dropped my item?
I would expect to find the index somewhere in the DragEventArgs of the Drop event, but I can't find it anywhere:
private async void ListView2_Drop(object sender, DragEventArgs e)
{
}
Anyway: I have tinkered around with this code and finally got it to work to my needs:
private async void MyListView_Drop(object sender, DragEventArgs e)
{
var scrollViewer = VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(MyListView, 0), 0) as ScrollViewer;
var position = e.GetPosition((ListView)sender);
var positionY = scrollViewer.VerticalOffset + position.Y;
var index = GetItemIndex(positionY, MyListView);
// do something useful with the index...
}
int GetItemIndex(double positionY, ListView targetListView)
{
var index = 0;
double height = 0;
foreach (var item in targetListView.Items)
{
height += GetRowHeight(item, targetListView);
if (height > positionY) return index;
index++;
}
return index;
}
double GetRowHeight(object listItem, ListView targetListView)
{
var listItemContainer = targetListView.ContainerFromItem(listItem) as ListViewItem;
var height = listItemContainer.ActualHeight;
var marginTop = listItemContainer.Margin.Top;
return marginTop + height;
}
Thank you for pointing me in the right direction!