private bool MoveItem(object item, int toIndex)
{
object itemsSource = this.ItemsSource;
System.Collections.IList sourceList = itemsSource as System.Collections.IList;
if (!(sourceList is System.Collections.Specialized.INotifyCollectionChanged))
{
// If the source does not implement INotifyCollectionChanged, then there's no point in
// changing the source because changes to it will not be synchronized with the list items.
// So, just change the ListBox's view of the items.
sourceList = this.Items;
}
int fromIndex = sourceList.IndexOf(item);
if (fromIndex != toIndex)
{
double scrollOffset = this.scrollViewer.VerticalOffset;
sourceList.RemoveAt(fromIndex);
sourceList.Insert(toIndex, item);
if (fromIndex <= scrollOffset && toIndex > scrollOffset)
{
// Correct the scroll offset for the removed item so that the list doesn't appear to jump.
this.scrollViewer.ScrollToVerticalOffset(scrollOffset - 1);
}
return true;
}
else
{
return false;
}
}