Listbox drag-reorder:已删除项目的索引
我正在使用 Listbox
包装在一个 ListBoxDragDropTarget
(从Silverlight工具包)。
这个 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.
我的问题如下:有没有办法知道删除的项目的新的索引?这样,如果索引=列表的最后一个位置,我可以将其移动到最后的位置。
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.