获取Silverlight拖放中的drop index

时间:2010-09-24 21:06:34

标签: silverlight drag-and-drop silverlight-toolkit

article显示了如何在drop事件上实现复制操作。我想做同样的事情,但我希望我删除的项目根据它放在UI上的位置出现在集合中。因此,当ObservableCollection发生更改时,我需要与NotifyCollectionChangedEventArgs类似的StartIndex。在本文中,您将看到最终获得的SelectionCollection对象,其项目具有Index属性。但不幸的是,这是源集合的索引(它被选中)而不是目标集合(它被删除的地方)。

1 个答案:

答案 0 :(得分:1)

好的,这很难看,但我没有找到另一种方式,不是靠自己,也不是通过搜索网络寻找答案。一定是微软的另一个截止日期,阻止了相当明显的功能被包括在内......

基本上,下面的方法手动执行所有操作,获取放置位置并检查列表框项目以用作索引引用。

private void ListBoxDragDropTarget_Drop(object sender, Microsoft.Windows.DragEventArgs e)
{
    // only valid for copying
    if (e.Effects.HasFlag(DragDropEffects.Copy))
    {
        SelectionCollection selections = ((ItemDragEventArgs)e.Data.GetData("System.Windows.Controls.ItemDragEventArgs")).Data as SelectionCollection;
        int? index = null;

        if (selections != null)
        {
            Point p1 = e.GetPosition(this.LayoutRoot); // get drop position relative to layout root
            var elements = VisualTreeHelper.FindElementsInHostCoordinates(p1, this.LayoutRoot); // get ui elements at drop location

            foreach (var dataItem in this.lbxConfiguration.Items) // iteration over data items
            {
                // get listbox item from data item
                ListBoxItem lbxItem = this.lbxConfiguration.ItemContainerGenerator.ContainerFromItem(dataItem) as ListBoxItem;

                // find listbox item that contains drop location
                if (elements.Contains(lbxItem))
                {
                    Point p2 = e.GetPosition(lbxItem); // get drop position relative to listbox item
                    index = this.lbxConfiguration.Items.IndexOf(dataItem); // new item will be inserted immediately before listbox item
                    if (p2.Y > lbxItem.ActualHeight / 2)
                        index += 1; // new item will be inserted after listbox item (drop location was in bottom half of listbox item)

                    break;
                }
            }

            if (index != null)
            {
                foreach (var selection in selections)
                {
                    // adding a new item to the listbox - adjust this to your model
                    (lbxConfiguration.ItemsSource as IList<ViewItem>).Insert((int)index, (selection.Item as ViewItem).Clone());
                }
            }
        }
    }
}