Listbox drag-reorder : 放置项的索引 [英] Listbox drag-reorder : Index of the dropped item
问题描述
我使用的是包裹在 ListBoxDragDropTarget
(来自 Silverlight 工具包)中的 Listbox
.这个 ListBox
可以由用户手动重新排序.但是,最后一项必须始终位于 ListBox
的底部,并且根本不能移动.我找到了一种取消最后一项移动的方法,但是如果我在最后一项下面拖放另一个项目,它会被移动.
I'm using a Listbox
wrapped inside a ListBoxDragDropTarget
(from the Silverlight toolkit).
This ListBox
ca be manually reordered by the user. However the last item must always be located at the bottom of the ListBox
, and can't be moved at all. I found a way to cancel this last item moves, but if I drag and drop another item below this last item, it gets moved.
我可以在 ListBox 的 Drop
事件中使用此代码找到拖动项的索引:
I can find the index of the dragged item using this code in the Drop
event of the ListBox:
object data = e.Data.GetData(e.Data.GetFormats()[0]);
ItemDragEventArgs dragEventArgs = data as ItemDragEventArgs;
SelectionCollection selectionCollection = dragEventArgs.Data as SelectionCollection;
if (selectionCollection != null)
{
MyClass cw = selectionCollection[0].Item as MyClass;
int idx = selectionCollection[0].Index.Value;
}
然而,这只给了我拖拽操作之前的索引.
However this only gives me the index before the drag operation.
我的问题如下:有没有办法知道删除项目的新索引?这样,如果index = list的最后一个位置,我就可以把它移到最前面的位置.
My question is the following: Is there a way to know the new index of the dropped item ? This way, if the index = last position of the list, I can move it to the forelast position.
提前致谢!
推荐答案
好的,我找到了一种方法.我绑定了 ListBoxDragDropTarget
的 ItemDragCompleted
事件,并执行了以下操作:
Ok I found a way to do this. I bound the ItemDragCompleted
event of the ListBoxDragDropTarget
, and did the following:
private void dropTarget1_ItemDragCompleted(object sender, ItemDragEventArgs e)
{
var tmp = (e.DragSource as ListBox).ItemsSource.Cast<MyClass>().ToList();
SelectionCollection selectionCollection = e.Data as SelectionCollection;
if (selectionCollection != null)
{
MyClass cw = selectionCollection[0].Item as MyClass;
int idx = tmp.IndexOf(cw);
if (idx == tmp.Count - 1)
{
tmp.Remove(cw);
tmp.Insert(tmp.Count - 1, cw);
MyListBox.ItemsSource = new ObservableCollection<MyClass>(tmp);
}
}
}
由于 DragSource 代表列表框,使用新的项目排列",因此我可以检查项目现在是否位于末尾,并在这种情况下移动它.
As the DragSource represents the Listbox, with the new "arrangement" of items, I can therefore check if the item is now located at the end, and move it in this case.
剩下的唯一问题是它会导致屏幕闪烁,因为项目被放下然后移动.
The only problem left is that it causes a flicker on the screen, due to the item being dropped and then moved.
我仍然愿意接受任何其他(最佳)建议.
I'm still open to any other (best) suggestion.
这篇关于Listbox drag-reorder : 放置项的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!