问题描述
我正在使用包装在 ListBoxDragDropTarget
中的 Listbox
(来自 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.
我的问题如下:有没有办法知道被丢弃项目的 new 索引?这样,如果 index = 列表的最后一个位置,我可以将它移动到最前面的位置.
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 : 拖放项的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!