考慮下面的XAML代碼:
<Grid x:Name="ListBoxDragDropTarget"
Background="Gold"
AllowDrop="True"
Drop="ListBoxDragDropTarget_Drop">
<ListBox x:Name="MyListBox" Margin="50">
<ListBoxItem Content="Item 1" />
<ListBoxItem Content="Item 2" />
<ListBoxItem Content="Item 3" />
</ListBox>
</Grid>
如果你想知道用戶在其上掉落的物品的ListBoxItem中您可以使用e.GetPosition
讓鼠標和VisualTreeHelper.FindElementsInHostCoordinates
的命中測試位置:
private void ListBoxDragDropTarget_Drop(object sender, DragEventArgs e)
{
Point position = e.GetPosition(this.ListBoxDragDropTarget);
var hits = VisualTreeHelper.FindElementsInHostCoordinates(position, this.ListBoxDragDropTarget);
ListBoxItem dropElement = hits.FirstOrDefault(i => i is ListBoxItem) as ListBoxItem;
if (dropElement != null)
{
// Do something with the dropElement... or if you want the index use ItemContainerGenerator
int index = this.MyListBox.ItemContainerGenerator.IndexFromContainer(dropElement);
}
}