获取Silverlight拖放中的drop index

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

解决方法

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

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

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());
                }
            }
        }
    }
}

相关文章

如何在Silverlight4(XAML)中绑定IsEnabled属性?我试过简单的...
我正在编写我的第一个vb.net应用程序(但我也会在这里标记c#,...
ProcessFile()是在UIThread上运行还是在单独的线程上运行.如...
我从同行那里听说,对sharepoint的了解对职业生涯有益.我们不...
我正在尝试保存一个类我的类对象的集合.我收到一个错误说明:...
我需要根据Silverlight中的某些配置值设置给定控件的Style.我...