silverlight - 在 Silverlight 拖放中获取放置索引

标签 silverlight drag-and-drop silverlight-toolkit

article展示了如何在 drop 事件上实现复制操作。我想做同样的事情,但我希望我的掉落元素根据它在 UI 上的位置出现在集合中。因此,当 ObservableCollection 更改时,我需要 StartIndex 就像 NotifyCollectionChangedEventArgs 一样。在本文中,您将看到最终您将获得一个 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());
                }
            }
        }
    }
}

关于silverlight - 在 Silverlight 拖放中获取放置索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3790986/

相关文章:

asp.net - 无法检索单个实体

C# 通用类型事件参数

java - 通过 ACTION_DRAG_LOCATION 滚动 GridView 并在 ACTION_DROP 上交换 Gridview 的 ArrayAdapter 中的项目

JavaFX在拖放完成后获取拖放目标文件夹

silverlight - 如何找到绑定(bind)到属性的所有目标依赖属性?

silverlight - 绑定(bind)到 Silverlight 中的 const 字段

xaml - 如何确定页面过渡动画何时结束?

c# - 使用 Toolkit for Windows Phone 中的 ExpanderView 自定义 header

javascript - JQuery UI 拖放而不拖放

windows-phone-7 - 在墓碑后恢复 LongListSelector 中的滚动位置